本文介绍了在安卓中.检查移动数据是打开还是关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用需要一个功能来检查用户的手机是否打开了移动数据.

My app need a function to check user's mobile phone has turned on the mobile data or not.

我参考了这个链接:#32239785

这是该主题中提供的代码

Here is the code provided in that topic

boolean mobileYN = false;

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
    {
        mobileYN = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
    }
    else{
        mobileYN = Settings.Secure.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
    }
}

此代码适用于我的大部分手机.

This code works in most of my mobile phone.

诺基亚 8"(Android 9)除外

Except on "Nokia 8"(Android 9)

即使我关闭了移动数据.这个函数仍然返回true.

Even I turned off the mobile data. This function still return true.

为什么?

推荐答案

检查一下,如果有帮助:

Check with this, if it helps:

class InternetNetwork {
companion object {
    fun isOnline(context: Context): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val capabilities =
                connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
            if (capabilities != null)
                when {
                    capabilities.hasTransport(TRANSPORT_CELLULAR) -> {
                        Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
                        return true
                    }
                    capabilities.hasTransport(TRANSPORT_WIFI) -> {
                        Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
                        return true
                    }
                    capabilities.hasTransport(TRANSPORT_ETHERNET) -> {
                        Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
                        return true
                    }
                }
        } else {
            val connectivityManage =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val netInfo = connectivityManage.activeNetworkInfo
            return netInfo != null && netInfo.isConnected
        }

        return false
    }
}
}

这篇关于在安卓中.检查移动数据是打开还是关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 14:11