0

如果网络不可用,我的代码不会显示 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();
        }
    }
}

实用类:

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;
 }
4

2 回答 2

0

尝试更改您的互联网连接代码:

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();}
于 2013-08-15T06:11:37.980 回答
0

试试这个对我有用...有请求权限 android.permission.ACCESS_NETWORK_STATE

public class HomeMenu extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homemenu);
    if (!isUserOnline(this)) {
        toast("No Network");
    }

}

public static boolean isUserOnline(Context context) {
    try {
        ConnectivityManager nConManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (nConManager != null) {
            NetworkInfo nNetworkinfo = nConManager.getActiveNetworkInfo();

            if (nNetworkinfo != null) {
                return nNetworkinfo.isConnected();
            }
        }
    } catch (Exception e) {
    }
    return false;
}

void toast(String message) {
    Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

}

于 2013-08-15T06:11:51.183 回答