android – ConnectivityManager getActiveNetworkInfo()返回null

我有一个功能检查是否有可用的网络连接,我注意到它已经崩溃了一些用户.这是功能:

public static boolean isOnline() {
    ConnectivityManager connectionManager = (ConnectivityManager) RouteForMeApplication.getInstance()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectionManager == null) return false;
    boolean networkAvailable = connectionManager.getActiveNetworkInfo() != null
            && connectionManager.getActiveNetworkInfo().isConnected();
    return networkAvailable;
}

而我得到的错误:

java.lang.NullPointerException
   at com.route4me.routeoptimizer.utils.InternetUtils.isOnline(InternetUtils.java:14)
   at com.route4me.routeoptimizer.services.notes.SendNoteServiceDeferred.sendNote(SendNoteServiceDeferred.java:57)
   at com.route4me.routeoptimizer.services.notes.SendNoteServiceDeferred.performAction(SendNoteServiceDeferred.java:28)
   at com.route4me.routeoptimizer.services.AbstractService$2.run(AbstractService.java:75)
   at java.lang.Thread.run(Thread.java:841)

我不明白的是,为什么它仍然返回null,即使我正在检查getActiveNetworkInfo()是否为null.有任何想法吗?

EDIT1
该错误出现在“&& connectionManager.getActiveNetworkInfo().isConnected();”行上

解决方法:

很容易成为竞争条件.假设如果connectionManager.getActiveNetworkInfo()!= null为真,则在一纳秒后再次为真是不安全的.

像这样改写:

public static boolean isOnline() {
    ConnectivityManager connectionManager = (ConnectivityManager) RouteForMeApplication.getInstance()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectionManager == null) {
        return false;
    }
    NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo()
    if (networkInfo == null) {
        return false;
    }
    return networkInfo.isConnected();
}
上一篇:java – 从共享首选项获取值时出现空指针异常


下一篇:java – getApplicationContext()返回null,但适用于其他活动