【问题标题】:ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService returning null on loadConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService 在加载时返回 null
【发布时间】:2018-07-16 01:46:13
【问题描述】:

加载应用程序时,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上的错误

【问题讨论】:

  • 我在该 logcat 屏幕截图中没有看到任何表明连接管理器为空的内容
  • 它指出了final ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
  • 我更新了这个问题。我附上了截图
  • 你在哪里使用那个代码?
  • OnCreateView

标签: android android-connectivitymanager


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-13
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多