Learning Android
Learning Android

Reputation: 273

internet connection error blocking the app

I have an app that needs internet, when the internet is excellent it works perfectly when there is no internet it works also perfectly because I've adde this code to check wether there is internet or not:

private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

and if it returns false I make a toast to the user saying that there's no internet;

but when the internet is poor the app gets an error or it just blocks and gets a black screen for 30sec and then show the error... so what can I do to fix this how can I see if internet is poor and avoid this...

Upvotes: 1

Views: 390

Answers (3)

laalto
laalto

Reputation: 152817

You can make the timeouts shorter than 30000 milliseconds to give up earlier. But there really isn't a way to make a poorly working connection work correctly.

Upvotes: 0

sujoy
sujoy

Reputation: 135

To perform network based operation, AsyncTask should be the choice.

Upvotes: 0

Piyush
Piyush

Reputation: 18933

Use this one:

public boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager)this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {

        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {

                    return true;
                }

    }

    return false;
}

Now check in your Activity.

 if(isConnectingToInternet()){

   // do your stuff using internet

 } else{

   // display Toast here

 }

Upvotes: 1

Related Questions