Android检测网络状态,开启Wifi

时间:2022-04-16 15:20:41
private boolean CheckWifiNetworkStatus() {
boolean flag = false;
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager.getActiveNetworkInfo() != null){
flag = manager.getActiveNetworkInfo().isAvailable();
}
if (!flag) {
Builder b = new AlertDialog.Builder(this).setTitle("没有可用的GPRS或WIFI网络").setMessage("开启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;
}


在AndroidManifest.xml中加入权限


    <!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />