ConnectivityManager connMgr =(ConnectivityManager)getContext()。getSystemService在加载时返回null

时间:2018-07-16 01:46:14

标签: android android-connectivitymanager

加载应用程序时,我在ConnectivityManager中遇到错误。我已经使用了很多,但这是我第一次遇到它。

它说为空,但我不知道此错误是什么原因。

这是我的代码:

   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

上的错误

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

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

try {
    final ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    ...
} catch (Exception e) {
    ...
}

答案 1 :(得分: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;
    }