android 如何以编程方式检查数据漫游是否启用/禁用?

x759pob2  于 2023-03-16  发布在  Android
关注(0)|答案(5)|浏览(269)

我正在检查用户是否启用/禁用了数据漫游。到目前为止,我发现您可以使用TelephonyManager.isNetworkRoaming()和NetworkInfo.isRoaming()检查用户当前是否处于漫游状态,但它们不是我需要的。

oknwwptz

oknwwptz1#

根据Nippey的回答,对我有效的代码片段是:

public Boolean isDataRoamingEnabled(Context context) {
    try {
        // return true or false if data roaming is enabled or not
        return Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.DATA_ROAMING) == 1;
    } 
    catch (SettingNotFoundException e) {
        // return null if no such settings exist (device with no radio data ?) 
        return null;
    }
}
g0czyy6m

g0czyy6m2#

您可以通过请求漫游交换机的状态

ContentResolver cr = ContentResolver(getCurrentContext());
Settings.Secure.getInt(cr, Settings.Secure.DATA_ROAMING);

参见:http://developer.android.com/reference/android/provider/Settings.Secure.html#DATA_ROAMING

50few1ms

50few1ms3#

public static final Boolean isDataRoamingEnabled(final Context application_context)
{
    try
    {
        if (VERSION.SDK_INT < 17)
        {
            return (Settings.System.getInt(application_context.getContentResolver(), Settings.Secure.DATA_ROAMING, 0) == 1);
        }

        return (Settings.Global.getInt(application_context.getContentResolver(), Settings.Global.DATA_ROAMING, 0) == 1);
    } 
    catch (Exception exception)
    {
        return false;
    }
}
f0brbegy

f0brbegy4#

已更新函数以说明API弃用。现在将其替换为:http://developer.android.com/reference/android/provider/Settings.Global.html#DATA_ROAMING

public static boolean IsDataRoamingEnabled(Context context) {
    try {
        // return true or false if data roaming is enabled or not
        return Settings.Global.getInt(context.getContentResolver(), Settings.Global.DATA_ROAMING) == 1;
    } 
    catch (SettingNotFoundException e) {
        return false;
    }
}
q43xntqr

q43xntqr5#

设置.全局.DATA_ROAMING现在为目标SDK 33或更高版本引发SecurityException。对于API 33和更高版本,您可以使用TelephonyManager.isDataRoamingEnabled。

TelephonyManager.isDataRoamingEnabled需要下列权限之一:Manifest.permission.ACCESS_NETWORK_STATEManifest.permission.READ_PHONE_STATEManifest.permission.READ_BASIC_PHONE_STATE
如需了解更多信息:https://developer.android.com/reference/android/telephony/TelephonyManager#isDataRoamingEnabled()

public static boolean isDataRoamingEnabled(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        boolean hasFeature = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_DATA);
        return hasFeature && telephonyManager.isDataRoamingEnabled();
    } else  {
        final ContentResolver contentResolver = context.getContentResolver();
        return android.provider.Settings.Global.getInt(
                contentResolver,
                android.provider.Settings.Global.DATA_ROAMING,
                0) == 1;
    }
}

相关问题