我当前正在编写一个应用,我想在其中检测Android设备当前连接到的网络类型(2G,3G或LTE)。我尝试使用以下解决方案:
"paths": {
"src": {
"base": "./src/",
"css": "./src/css/",
"json": "./src/json/",
"js": "./src/js/",
"scss": "./src/scss/"
},
"dist": {
"base": "./public/",
"css": "./public/css/",
"js": "./public/js/",
"material": "./public/js/@material/"
},
"build": {
"base": "./build/",
"css": "./build/css/",
"js": "./build/js/",
"html": "./build/html/"
}
},
"globs": {
"babelJs": [
"./src/js/**/*.js"
]
}
和连接管理器:
gulp.task('js-babel', function() {
console.log($.chalk.yellow.bold('--> Transpiling Javascript via Browserify & Babelify...'));
let files = $.glob.sync(''+pkg.globs.babelJs+'');
// map them to streams
let tasks = files.map(function(entry) {
return $.browserify({ entries: [entry] })
.transform('babelify')
.bundle()
.pipe($.vinylSourceStream(entry))
.pipe($.flatten()) // Important!!!!
.pipe(gulp.dest(pkg.paths.build.js))
.pipe($.size({gzip: true, showFiles: true}));
});
// merge
return $.eventStream.merge.apply(null, tasks);
});
这两种方法都可以在没有WiFi连接的情况下正常工作,但是如果连接到WiFI,则TelephonyManager返回https://developer.android.com/reference/android/telephony/TelephonyManager#NETWORK_TYPE_IWLAN,而ConnectivityManager返回0(未知)。
即使电话已连接到WiFi网络,是否可以找到电话是否已连接2G,3G或LTE?
答案 0 :(得分:1)
问题在于,在API版本24和向前的getNetworkType()中,该方法已分为两个单独的方法:
和
我在代码中添加了一个检查,以检查返回的类型是否为IWLAN,如果是,则使用getVoiceNetworkType()代替。
if (tm.getNetworkType() != 18)
return tm.getNetworkType();
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
return tm.getVoiceNetworkType();
else
return -1;
答案 1 :(得分:0)
您可以尝试使用getAllNetworks()
中的ConnectivityManager
来跟踪所有活动的网络。
请参阅此处: https://developer.android.com/reference/android/net/ConnectivityManager#getAllNetworks()
您可以使用getNetworkInfo()
答案 2 :(得分:0)
调用此方法
public void checkNetworkType(){
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA)) {
Toast.makeText(this, "3G network type", Toast.LENGTH_LONG).show();
} else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPAP)) {
Toast.makeText(this, "4G network type", Toast.LENGTH_LONG).show();
} else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_GPRS)) {
Toast.makeText(this, "GPRS network type", Toast.LENGTH_LONG).show();
} else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE)) {
Toast.makeText(this, "2G network type", Toast.LENGTH_LONG).show();
}
}