Hi I'm working on an Android App which has the possibility of connecting to a server. This application can work online or offline. For connection to the server, I use AsyncTask, which and in doInBackground
is where I do all the network operations. Then I create a new instance of the Asynctask when I click a button.
What I would like to know is if there is a way of checking if the server is active in order to launch the AsyncTask. I have thought of try and catch but I would like to know if there is a better solution
Use this code snippet for checking network connectivity before executing the AsyncTask.
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
boolean isConnected = netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED;
Do not forget to add the permission in the manifest.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />