NetInfoModule
向JS端提供了当前设备的网络状态信息,API方法如下:
- getCurrentConnectivity 异步返回网络状态network_info
- isConnectionMetered 返回手机流量是否被计量
实现分析如下。
NetInfoModule
创建时会获取系统服务:
mConnectivityManager = (ConnectivityManager) reactContext.getSystemService(Context.CONNECTIVITY_SERVICE);
JS端获取手机网络状态信息的方式有两种,一种是调用异步方法主动拉取,另一种是当手机状态改变的时候Native主动通知JS端。
通过getCurrentConnectivity方法,JS端可以主动拉取到当前设备的网络状态:
public void getCurrentConnectivity(Promise promise) {
if (mNoNetworkPermission) {
promise.reject(ERROR_MISSING_PERMISSION, MISSING_PERMISSION_MESSAGE, null);
return;
}
promise.resolve(createConnectivityEventMap());
}
private WritableMap createConnectivityEventMap() {
WritableMap event = new WritableNativeMap();
event.putString("network_info", mConnectivity);
return event;
}
成员变量mConnectivity
保存了当前网络状态。
NetInfoModule
注册了网络状态改变广播的监听:
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getReactApplicationContext().registerReceiver(mConnectivityBroadcastReceiver, filter);
mConnectivityBroadcastReceiver.setRegistered(true);
}
private void unregisterReceiver() {
if (mConnectivityBroadcastReceiver.isRegistered()) {
getReactApplicationContext().unregisterReceiver(mConnectivityBroadcastReceiver);
mConnectivityBroadcastReceiver.setRegistered(false);
}
}
当收到网络状态发生改变的系统广播后,一方面更新成员变量mConnectivity
,一方面主动通知JS端:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
updateAndSendConnectionType();
}
}
private void updateAndSendConnectionType() {
String currentConnectivity = getCurrentConnectionType();
if (!currentConnectivity.equalsIgnoreCase(mConnectivity)) {
mConnectivity = currentConnectivity;
sendConnectivityChangedEvent();
}
}
当用户处于非WIFI环境下时,往往会比较在意网络流量问题。isConnectionMetered相当于返回了当前用户是否在意流量的耗费:
public void isConnectionMetered(Promise promise) {
if (mNoNetworkPermission) {
promise.reject(ERROR_MISSING_PERMISSION, MISSING_PERMISSION_MESSAGE, null);
return;
}
promise.resolve(ConnectivityManagerCompat.isActiveNetworkMetered(mConnectivityManager));
}
为了便于使用,JS端对NetInfoModule模块进行了封装,可以直接使用NetInfo类获取网络信息。