我有一个功能,检查是否有可用的网络连接,我注意到它崩溃了一些用户。这是函数:
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)
我不明白的是,尽管我正在检查getactivenetworkinfo()是否为空,但它为什么仍然返回空值。有什么想法吗?
编辑1
错误在“&&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();
}