Example of android detecting network connection status
- 2020-05-30 21:01:52
- OfStack
First of all, to judge the network state, you need to have the corresponding permission. The following is the permission code (AndroidManifest.xml) :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
It then detects whether the network state is available
/**
* Determine the network connection status
* @return true, Available; false . Do not use
*/
private boolean isOpenNetwork() {
ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connManager.getActiveNetworkInfo() != null) {
return connManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
Finally, unavailability turns on network Settings
/**
* Visit baidu homepage, the network is not available then need to set
*/
private void initMoreGames() {
String URL_MOREGAMES = "http://www.baidu.com";
mWebView = (WebView) findViewById(R.id.view_gamesort);
if (mWebView != null) {
mWebView.requestFocus();
WebSettings webSettings = mWebView.getSettings();
if (webSettings != null) {
webSettings.setJavaScriptEnabled(true);
webSettings.setCacheMode(MODE_PRIVATE);
webSettings.setDefaultTextEncodingName("utf-8");
}
// Determine if the network is available
if(isOpenNetwork() == true) {
mWebView.loadUrl(URL_MOREGAMES);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MoreGamesActivity.this);
builder.setTitle(" No network is available ").setMessage(" Whether to set up the network ?");
builder.setPositiveButton(" is ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
try {
String sdkVersion = android.os.Build.VERSION.SDK;
if(Integer.valueOf(sdkVersion) > 10) {
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else {
intent = new Intent();
ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(comp);
intent.setAction("android.intent.action.VIEW");
}
MoreGamesActivity.this.startActivity(intent);
} catch (Exception e) {
Log.w(TAG, "open network settings failed, please check...");
e.printStackTrace();
}
}
}).setNegativeButton(" no ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
}).show();
}
} else {
Log.w(TAG, "mWebView is null, please check...");
}
}