Android 正在检测 Internet 连接问题的类型

Android Detecting type of Internet Connection issue

大家好,我在检测 phone 上的 Internet 连接类型时遇到了问题。所以我使用我的代码,发生的事情是,当我使用 wifi 时,应用程序 returns 对我来说是 Wifi 类型,但是当我使用 3g 连接时,我收到一条消息,说应用程序已关闭。谁能给我一些建议?非常感谢。

这是我的代码。

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

以及我在清单中的权限。

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

有什么想法吗?

文档说:

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

因此,也许您的 info 变量为 NULL,当您未连接到任何网络时会导致崩溃。

将您的代码更改为:

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