You can use ConnectivityManager class , with a simple alert dialogue , in order to make sure that user is having internet connection , for example:
private NetworkState mNetworkState;
mNetworkState = new NetworkState(mContext);
if (!mNetworkState.isConnected()) {
/**
If application is not connected to the internet , then
display dialog message and finish.
*/
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
mContext);
// set dialog message
alertDialogBuilder
.setMessage("This application needs internet connection.")
.setCancelable(false).setPositiveButton("Got it!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
/**
In my case i close the current activity , by calling finish()
*/
MainActivity.this.finish();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} else {
/**
YOUR CODE GOES HERE :
*/
}
and for Network State class will be :
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
// This class for accessing network state for our application
public class NetworkState {
private final ConnectivityManager mConnectivityManager;
public NetworkState(Context context) {
mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
public boolean isConnected() {
NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
} }