目录
加载包
importClass(android.content.BroadcastReceiver);
importClass(android.content.ContextWrapper);
importClass(android.content.IntentFilter);
importClass(android.net.ConnectivityManager);
获取网络类型
var mConnectivityManager = context.getSystemService(context.CONNECTIVITY_SERVICE);
netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isAvailable()) {
if(!device.isScreenOn() && !device.isCharging()){
device.keepScreenOn(100)
}
var name = netInfo.getTypeName();
if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
console.log("WiFi网络");
return "WiFi网络"
} else if (netInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
console.log("有线网络");
return "有线网络"
} else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
console.log("3g网络");
return "3g网络"
}
} else {
console.log("网络断开");
return "网络断开"
}
监听网络状态改变广播
function internetCheck() {
var intent = new Intent();
var filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
let r = new BroadcastReceiver({
onReceive: function (context, intent) {
var action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
getInternetType()
}
}
})
new ContextWrapper(context).registerReceiver(r , filter);
events.on("exit", function () {
new ContextWrapper(context).unregisterReceiver(r)
});
}
问题
翻安卓文档的时候发现
NetworkInfo类在 level 29 已经废弃,目前暂时能用先用着。有时间再研究。
https://developer.android.com/reference/android/net/NetworkInfo