ConnectivityManager如何确定当前网络上是否存在连接

时间:2015-11-06 10:55:30

标签: android

您可以使用此片段here

检查Android上是否存在连接
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork.isConnectedOrConnecting();

但是ConnectivityManager需要说明设备当前是否已连接且功能正常的数据?

正如ConnectivityManager.java文件NetworkInfo的 AOSP 源代码所示,它只是ConnectivityManager构建的信息的容器。但是ConnectivityManager会从名为IConnectivityManager接口中获取所有数据。我在这里失去了踪迹。

public NetworkInfo getActiveNetworkInfo() {
    try {
        return mService.getActiveNetworkInfo();
    } catch (RemoteException e) {
        return null;
    }
}

有人可以在这里点亮一点吗?

1 个答案:

答案 0 :(得分:1)

ConnectivityManager拨打ConnectivityServicegetActiveNetworkInfo

@Override
public NetworkInfo getActiveNetworkInfo() {
    enforceAccessPermission();
    final int uid = Binder.getCallingUid();
    NetworkState state = getUnfilteredActiveNetworkState(uid);
    return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
}
  • 致电getUnfilteredActiveNetworkState [1]
  • 然后拨打getDefaultNetwork [2]
  • 然后从NetworkAgentInfo SparseArray [3]
  • 获取mNetworkForRequestId