Show no Internet connection in Android Studio
Show no Internet connection in Android Studio
In this article we will learn that how to show No Internet Connection Dialog. It is very pretty simple though. Showing No Internet Connection Dialog is very helpful in app like WebView app and all other apps which are mainly dependent on Internet to work. Making this is very easy and just take few minutes.
First you need to add below permission to your manifest file.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Next go to your MainActivity.Java and below methods below onCreate Method.
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or wifi to access this. Press ok to Exit");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder;
}
You may get many errors here click on the error text and press Alt+Enter on your keyboard. Repeat the step for all error text like this.
Next replace below line of code in MainActivity.Java
setContentView(R.layout.activity_main);
with below code
if(!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
else {
Toast.makeText(MainActivity.this,"Welcome", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
}
Note:- Now run the code on your phone with Mobile data and WiFi connection turned off to see the desired output i.e, No Internet connection Dialog when there is no internet connection on your Android Device
Tags:
Android Studio
0 comments
Please leave your comments...... Thanks