Breaking

LightBlog

Sunday, June 4, 2017

Check Network Available or Not





Do you face a any situation to check internet connection availability before do some network related stuff. If yes, Today I am going to give some code snippet to check your your internet connection.


First Add this code to the manifest.


<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


in first permission it will add access internet connection permission to the app. The second permission allow check network state from the app. We need both this permission to check internet connection.

Next add this code to Activity or class which you need to check internet connection.



public boolean isNetworkConnectionAvailable(){
    ConnectivityManager cm =
            (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnected();
    if(isConnected) {
        Log.d("Network", "Connected");
        return true;
        }
    else{
        showNetworkNotAvailableDialog();
        Log.d("Network","Not Connected");
        return false;
    }
}


public void showNetworkNotAvailableDialog(){
    AlertDialog.Builder builder =new AlertDialog.Builder(this);
    builder.setTitle("No internet Connection");
    builder.setMessage("Please turn on internet connection to continue");
    builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}



in this NetworkConnectionAvailable method check the network availability. If not it will call showNetworkNotAvailableDialog method and it will popup the alert which show network  not available .


Happy Android ðŸ˜Š
.

No comments:

Post a Comment

Adbox