NetInfoModule
向JS端提供了當(dāng)前設(shè)備的網(wǎng)絡(luò)狀態(tài)信息拓巧,API方法如下:
- getCurrentConnectivity 異步返回網(wǎng)絡(luò)狀態(tài)network_info
- isConnectionMetered 返回手機(jī)流量是否被計量
實(shí)現(xiàn)分析如下。
NetInfoModule
創(chuàng)建時會獲取系統(tǒng)服務(wù):
mConnectivityManager = (ConnectivityManager) reactContext.getSystemService(Context.CONNECTIVITY_SERVICE);
JS端獲取手機(jī)網(wǎng)絡(luò)狀態(tài)信息的方式有兩種彬向,一種是調(diào)用異步方法主動拉取逃片,另一種是當(dāng)手機(jī)狀態(tài)改變的時候Native主動通知JS端屡拨。
通過getCurrentConnectivity方法,JS端可以主動拉取到當(dāng)前設(shè)備的網(wǎng)絡(luò)狀態(tài):
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
保存了當(dāng)前網(wǎng)絡(luò)狀態(tài)。
NetInfoModule
注冊了網(wǎng)絡(luò)狀態(tài)改變廣播的監(jiān)聽:
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);
}
}
當(dāng)收到網(wǎng)絡(luò)狀態(tài)發(fā)生改變的系統(tǒng)廣播后呀狼,一方面更新成員變量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();
}
}
當(dāng)用戶處于非WIFI環(huán)境下時,往往會比較在意網(wǎng)絡(luò)流量問題哥艇。isConnectionMetered相當(dāng)于返回了當(dāng)前用戶是否在意流量的耗費(fèi):
public void isConnectionMetered(Promise promise) {
if (mNoNetworkPermission) {
promise.reject(ERROR_MISSING_PERMISSION, MISSING_PERMISSION_MESSAGE, null);
return;
}
promise.resolve(ConnectivityManagerCompat.isActiveNetworkMetered(mConnectivityManager));
}
為了便于使用绝编,JS端對NetInfoModule模塊進(jìn)行了封裝,可以直接使用NetInfo類獲取網(wǎng)絡(luò)信息貌踏。