0

我已经在 Play 商店中发布了我的应用程序,我正在使用以下方法检查网络状态:

public class TestInternetConnection {

    public boolean checkInternetConnection(Context context) {

         ConnectivityManager con_manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

         if (con_manager.getActiveNetworkInfo() != null && con_manager.getActiveNetworkInfo().isAvailable() && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}

Google Play 控制台中,我看到三星设备在checkInternetConnection使用Nullpointerexception. 问题是什么?在我的设备和其他设备上它工作得很好。

堆栈跟踪:

java.lang.NullPointerException: 
      at de.name.app.TestInternetConnection.checkInternetConnection (TestInternetConnection.java)
      at de.name.app.SubstitutionInfoFragment$2.run (SubstitutionInfoFragment.java)
      at java.lang.Thread.run (Thread.java:762)
4

2 回答 2

0

您需要像这样修改您的功能,这对我来说在所有设备上都可以正常工作。只是在继续之前添加对上下文的空检查。

public static boolean checkInternetConnection(Context context) {
    // Add a null check before you proceed
    if (context == null) return false;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null && info.isConnected();
}
于 2017-09-30T08:24:12.087 回答
0

Reaz Murshed 的回答应该可以解决您眼前的问题,但在此之前,我认为您应该仔细检查堆栈跟踪并找出您的应用程序将null上下文传递到的确切位置checkInternetConnection。这就是错误的真正来源。

于 2017-09-30T08:47:01.180 回答