/** * 校验网络,如果没有网络,返回true * * @return boolean */ @Override public boolean hasInternetConnected() { ConnectivityManager manager = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); if (manager != null){ NetworkInfo info = manager.getActiveNetworkInfo(); if(info !=null && info.isConnectedOrConnecting() ){ return true; } } openWirelessSet(); return false; }
/** * 弹出框 */ @Override public void openWirelessSet() { final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("提示") .setMessage("请检查您的网络连接") .setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent( Settings.ACTION_WIRELESS_SETTINGS); context.startActivity(intent); } }) .setNegativeButton("关闭", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); }
上面这种方式是我自己用的可以的
/** * 检验网络连接是否可用 * * @return boolean */ @Override public boolean validateInternet() { ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if(manager != null){ NetworkInfo[] info =manager.getAllNetworkInfo(); if (info != null){ for (NetworkInfo networkInfo : info){ if (networkInfo.getState() == NetworkInfo.State.CONNECTED); return true; } } } return false; }
这种也看别人用过,不过今天自己测试了一下,自己明明把网络数据给关了,但返回的还是true,不知道为什么(PS:有大神来解释一下呗)