0

ConnectivityManager加载应用程序时出现错误。我用过很多次,但这是我第一次遇到它。

它说 null 但我不知道这个错误是什么原因造成的。

这是我的代码:

   final ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (wifi.isConnected()) {
                baseUrl = URL1;
            } else if (mobile.isConnected()) {
                baseUrl = URL2;
            }

这是错误Logcat

在此处输入图像描述

在此处输入图像描述

4

2 回答 2

0

getContext()当您的活动被杀死或应用程序进入后台时,可能会变为空。由于这可能发生在运行时,请使用try-catch.

try {
    final ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    ...
} catch (Exception e) {
    ...
}
于 2018-07-16T03:19:56.870 回答
0
Please Use this code--
and make sure that you context should not be null.

    enter code here
public static boolean checkConnectivity(Context context){
        boolean isConnected = false;
        try{
            ConnectivityManager connService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo network = connService.getActiveNetworkInfo();
            if(network != null) {
                State state = network.getState();

                if(network.isConnected()){
                    isConnected = true;
                }
            }else{
                isConnected = false;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return isConnected;
    }
于 2018-07-16T12:04:04.357 回答