Jaume Colom Ferrer
Jaume Colom Ferrer

Reputation: 334

Checking a good connection in Android

Actually, I have a function to check the Internet Connection... that is:

public boolean isOnline() {
        ConnectivityManager cm =
            (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

But, if I have a low signal connection.. when I Log In my app and it takes a lot of time, it crashes. How can I do, if i want to check a good or fast connection? Like a timeout condition or something like that..

Thank you a lot!

Upvotes: 1

Views: 106

Answers (1)

Emanuel
Emanuel

Reputation: 8106

first of all you should make sure if (not) on wifi. Then you can check for the desired "speed" by using

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
int prov = tm.getNetworkType();

switch (prov) {
        case 1: return GPRS;
        case 2: return EDGE;
        case 3: return UMTS;
        case 8: return HSDPA;
        case 9: return HSUPA;
        case 10:return HSPA;
        default:return UNKNOWN;
        }

If you want to check the signal strength of the connected wifi (which does not guarantuee a good network!) you can use

WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level=WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5 /** this is how many levels MAX should be displayed **/);

as higher the level, as better the signal. You can also use yourwifi.level to get the dBm. -100 to 0. 0 is highest. cheers.

edit: and because of your "app crashes.". It sounds like that you are doing too many stuff into your main(ui/thread). Make sure it's in a own Thread or an AsyncTask for long-operating stuff.

Upvotes: 1

Related Questions