网络判断
首先在清单文件中进行注册:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
Android系统版本号对应api
然后创建一个网络工具类:NetUtilsWork
/**
* @author Martin-harry
* @date 2017/12/19
* @address
* @Desc 检查网络
*/
public class NetUtilsWork {
/**
* 判断手机是否联网
*
* @param context
* @return
*/
public static boolean isConn(Context context) {
boolean ConnFlag = false;
ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if (network != null) {
ConnFlag = conManager.getActiveNetworkInfo().isAvailable();
}
return ConnFlag;
}
/**
* 打开网络设置
* @param context
*/
public static void openNetSettingDg(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("设置网络");
builder.setMessage("是否要打开网络连接?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
// 判断当前系统版本
if (Build.VERSION.SDK_INT >= 10) {
// 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
}
在应用场景中,如下去调用检测网络的设置:
boolean b = NetUtils.isConn(this);
/**
*网络判断
*/
if(b){
Toast.makeText(this,"有网络",Toast.LENGTH_SHORT).show();
}else{
NetUtilsWork .openNetSettingDg(this);
Toast.makeText(this,"无网络",Toast.LENGTH_SHORT).show();
}