Android Detecting type of Internet Connection issue

183 views Asked by At

Hello everyone I am having trouble on detecting the type of Internet connection that I get on my phone. So I use my code and what happens is that when I am using wifi the application returns to me the type Wifi but when I am using 3g connection I get a message saying the application has closed. Anyone can give me some advice ? Many thanks.

So here is my code.

  TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);      

            Context context = getApplicationContext();
            CharSequence text = "Hello toast!";
            int duration = Toast.LENGTH_SHORT;

            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);      
            NetworkInfo info = cm.getActiveNetworkInfo();



            if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA)) {
                   text = "3g";// for 3g HSDPA networktype will be return as
                                        // per testing(real) in device with 3g enable data
                    // and speed will also matters to decide 3g network type
                } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPAP)) {
                    text= "4g"; // /No specification for the 4g but from wiki
                                            // i found(HSPAP used in 4g)
                                            // http://goo.gl/bhtVT
                } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_GPRS)) {
                     text= "GPRS"; 
                } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE)) {
                     text= "2g"; 
                }
                else if ((info.getType() == ConnectivityManager.TYPE_WIFI)
                        ) {
                 text= "WIFI"; 
               }



            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

And my permissions in the Manifest.

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Any idea ?

1

There are 1 answers

0
Radon8472 On BEST ANSWER

Documentation says:

Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.

http://developer.android.com/reference/android/net/ConnectivityManager.html#getActiveNetworkInfo%28%29

So maybe your info variable is NULL and causes a crash when you are not connected to any net.

change your code to:

else if ( info==null) {  text= "no network";  }
else if ((info.getType() == ConnectivityManager.TYPE_WIFI)
                        ) {
                 text= "WIFI"; 
               }