Android Runtime Internet connection check

If your app use internet connection on its Main Activity then you should check internet connection at the fist time of your app runs.if you did not internet connection at the first screen of your app and user internet connection if off, in that time your application will crush.that’s not good for user and also a developer. So we should check internet connection like this:

1 : First we check user internet Connection ON or OFF

If user internet connection is ON then we will do our task,and if internet connection is OFF then we will show a dialog to turn ON the internet connection

public void isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {

// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
Intent intent=new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
finish();

String.valueOf(true);
return;
}
else
{
//Toast.makeText(MainActivity.this, "No internet connection! , try again...", Toast.LENGTH_LONG).show();

showDialogTurnOnInternetConnection();

}
String.valueOf(false);
}

2: Now Create a method to show dialog


private void showDialogTurnOnInternetConnection() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage(R.string.info_lose_internet);
builder1.setCancelable(true);

builder1.setPositiveButton(
R.string.title_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
recreate();
}
});

builder1.setNegativeButton(
R.string.title_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});

AlertDialog alert11 = builder1.create();
alert11.show();
}

for dialog messages in your strings.xml add this lines

<string name="title_ok" translatable="false">OK</string>
<string name="title_cancel" translatable="false">Cancel</string>

<string name="info_lose_internet" translatable="false">No internet connection.Please check again!</string>

3 : At the last in your onCreate just call the isOnline method

isOnline();
Android Runtime check Internet Connection
Android Runtime check Internet Connection
One Comment

Add a Comment

Your email address will not be published. Required fields are marked *