我有一个功能检查是否有可用的网络连接,我注意到它已经崩溃了一些用户。这是功能:
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()是否为null,它仍然会返回null。有什么想法吗?
EDIT1 错误出现在"&& 。connectionManager.getActiveNetworkInfo()isConnected();"
答案 0 :(得分:6)
很容易成为竞争条件。假设如果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();
}
答案 1 :(得分:0)
要访问连接管理器,您需要在清单文件中添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
答案 2 :(得分:0)
private boolean CheckNetWorkState() {
final ConnectivityManager conMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr == null)
return false;
NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}