Reputation: 6939
I am a beginner in Android programming, I am trying to make Http requests to a remote server and I would like to check whether the user can connect to the net or not in order to avoid my app to crash due to the fail of an AsyncTask I am making.
I found this method:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
But when I try to call it inside the doInBackground AsyncTask method implementation the app crashes:
class RemoteThread extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(IMieiDati.this);
pDialog.setMessage("Caricamento...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... strings ){
// checking whether the network is not available
// but the app crashes here
if (!isNetworkAvailable()) {
Log.d("Message", "No Network Connection. Aborting.");
}
// here I should make the request if the network is available
}
...etc, etc...
How can I resolve and e.g. show a message to the user that says something like "We are sorry, in order to use the app properly, you should connect to the network" or anything like that?
Thanks!
Upvotes: 0
Views: 36
Reputation: 645
First it will better to check for network before executing the RemoteThread
class.
And also make sure you've added permissions to you application
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
Also check that your are importing right package
import android.content.Context;
Upvotes: 1