<uses-permission android:name= "android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
/** * 检查WIFI是否连接 * * @author Ysjian * @date 2014-5-9 * @return 如果连接了返回true,否则返回false */ public boolean isWifiConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); return wifiInfo != null; } /** * 检查手机网络(4G/3G/2G)是否连接 * * @author Ysjian * @date 2014-5-9 * @return 如果连接了返回true,否则返回false */ public boolean isMobileNetworkConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobileNetworkInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return mobileNetworkInfo != null; } /** * 检查是否有可用网络 * * @author Ysjian * @date 2014-5-9 * @return 存在WIFI和手机数据任意可用网络返回true,否则返回false */ public boolean hasActivityNetwork() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return connectivityManager.getActiveNetworkInfo() != null; }
if (!hasActivityNetwork()) { AlertDialog.Builder builder = new AlertDialog.Builder(this ); builder. setTitle( "没有可用的网络" ) .setMessage( "是否对网络进行设置?" ) .setPositiveButton( "是" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { Intent intent = null ; intent = newIntent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); startActivity(intent); } }) .setNegativeButton( "否" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); }文章来源:http://blog.csdn.net/ysjian_pingcx/article/details/25461053
Android实践--监测网络状态,布布扣,bubuko.com
原文:http://blog.csdn.net/ysjian_pingcx/article/details/25461053