Answer the question
In order to leave comments, you need to log in
How to handle a connection error when there is no internet on android?
In the absence of the Internet, the android application crashes immediately. I make all connections in AsyncTask and put the call in a try catch block
try{
new UpdateTask(getApplicationContext()).execute(params);
} catch (Throwable t) {
Toast.makeText(
getApplicationContext(),
"Ошибка соединения",
Toast.LENGTH_SHORT).show();
}
Answer the question
In order to leave comments, you need to log in
public class NetworkManager {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
}
if (NetworkManager.isNetworkAvailable(context)) {
// делаем спокойно запрос
} else {
// если сети нет показываем Тост или
// кидаем на активити с красивым дизайном где просим сделать реконнект
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I hope you have some kind of common parent class for such tasks, in its "execute" you can add a check for an Internet connection, and if it is not there, then do something else, or nothing.
to check for a connection:
and
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question