Android判断是否有可用网络的代码
16lz
2021-01-26
在开发基于网络的应用的时候,需要判断是否有可用的网络,如果没有开启WIFI或者APN的话,是无法连接网络的。以下代码是判断是否有网络,以及没有网络的话,打开系统设置进行开启。
private boolean CheckNetwork() {
boolean flag = false;
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cwjManager.getActiveNetworkInfo() != null)
flag = cwjManager.getActiveNetworkInfo().isAvailable();
if (!flag) {
Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage(getResources().getString("请开启GPRS或WIFI网络连接"));
b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent mIntent = new Intent("/");
ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
mIntent.setComponent(comp);
mIntent.setAction("android.intent.action.VIEW");
startActivity(mIntent);
}
}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}).create();
b.show();
}
return flag;
}
主要是通过Intent来调用开启网络的Activity。
private boolean CheckNetwork() {
boolean flag = false;
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cwjManager.getActiveNetworkInfo() != null)
flag = cwjManager.getActiveNetworkInfo().isAvailable();
if (!flag) {
Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage(getResources().getString("请开启GPRS或WIFI网络连接"));
b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent mIntent = new Intent("/");
ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
mIntent.setComponent(comp);
mIntent.setAction("android.intent.action.VIEW");
startActivity(mIntent);
}
}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}).create();
b.show();
}
return flag;
}
主要是通过Intent来调用开启网络的Activity。
更多相关文章
- Android(安卓)教你一步步搭建MVP+Retrofit+RxJava网络请求框架
- android网络与通信(三种网络接口简述 )
- adb code
- Android:使用Socket网络通信时异常:java.net.SocketException: soc
- Activity加载模式
- Android(判断wifi是否开启,手机屏幕状态,sdcard是否被拔出,设置全屏)
- Android(安卓)基于NetworkCallback的网络状态监听框架
- Android中从网络获取数据的方法
- 谈谈Android的三种网络通信方式