G
G
Gibbon Cho2014-08-06 13:20:35
Java
Gibbon Cho, 2014-08-06 13:20:35

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

3 answer(s)
F
FanKiLL, 2014-08-06
@FanKiLL

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;
        }
    }
}

and check the network before each request
if (NetworkManager.isNetworkAvailable(context)) {
    // делаем спокойно запрос
} else {
    // если сети нет показываем Тост или 
    // кидаем на активити с красивым дизайном где просим сделать реконнект
}

Requires a permishin, add a permishin to the manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

P
Push Pull, 2014-08-06
@deadbyelpy

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();
}

A
Alexander, 2014-08-06
@itvdonsk

You need to put an exception in the block that performs the connection. In your case, you need to put in the function doInBackground AsyncTask'a
PS You cannot show Toast from doInBackground AsyncTask'a

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question