如果没有网络连接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;
 }
Jave_
JaveZh 代码是没问题的,你的问题是?
6 年多之前 回复

1个回答

修改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
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问