2 bluetooth99 bluetooth99 于 2013.08.15 16:26 提问

如果没有网络连接Toast就不显示

如果网络连接不可用,我的Toast信息就不显示。代码如下:

public class HomeMenu extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homemenu);

        if (!Utils.isNetworkAvailable(HomeMenu.this)) {
            Toast.makeText(HomeMenu.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
        }
    }
}

Util 类:

public static boolean isNetworkAvailable(Activity activity) {
    ConnectivityManager connectivity = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
 }

1个回答

g989_1314125
g989_1314125   2013.08.15 17:13

修改Internet连接:

public static boolean isNetworkAvailable(Activity activity) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
    return true;
}
return false; }

检测onCreate()方法:

if (!Utils.isNetworkAvailable(HomeMenu.this)) {
       Showtoast("No Connection Available.");
    }
void Showtoast(String message) {
Toast.makeText(HomeMenu.this, message, Toast.LENGTH_LONG).show();}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!