在安卓双卡手机上,如何检测哪张SIM卡开启了数据?

3

我正在编写一个网络监视器应用程序。我想检测双卡手机中哪张SIM卡启用了数据?

我已经尝试使用TelephonyManager.isDataEnabled()方法来检测两张SIM卡的数据是否启用。但是该方法返回了两张SIM卡都启用的结果。相反,我应该得到一张SIM卡启用而另一张禁用的结果。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {

    SubscriptionManager subManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
    List<SubscriptionInfo> subscriptionInfoList = subManager.getActiveSubscriptionInfoList();

    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        TelephonyManager mgr = telephonyManager.createForSubscriptionId(subscriptionInfoList.get(0).getSubscriptionId());
            int isDataEnabledSIM1 = mgr.isDataEnabled()?1:0;

            mgr = telephonyManager.createForSubscriptionId(subscriptionInfoList.get(1).getSubscriptionId());
            int isDataEnabledSIM2 = mgr.isDataEnabled()?1:0;

            Log.d(TAG, "isDataEnabledSIM1: "+isDataEnabledSIM1 + ", isDataEnabledSIM2="+isDataEnabledSIM2);
    }
}

isDataEnabledSIM1和isDataEnabledSIM2都返回为1,表示两张SIM卡上都启用数据。这显然是不正确的,我期望只有一张SIM卡返回1,另外一张返回0。


类似:https://stackoverflow.com/questions/39823886/check-mobile-data-is-on-from-sim-one-or-sim-two-android - Darpan Rangari
1个回答

0

您可以使用SubscriptionManager中的getDefaultDataSubscriptionId()(适用于N及更高版本),在N以下版本中,您可以使用反射。例如:

public static int getDefaultDataSubscriptionId(Context context) {
    SubscriptionManager subscriptionManager = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
        subscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        int nDataSubscriptionId = SubscriptionManager.getDefaultDataSubscriptionId();

        if (nDataSubscriptionId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
            return (nDataSubscriptionId);
        }
    }

    try {
        Class<?> subscriptionClass = Class.forName(subscriptionManager.getClass().getName());
        try {
            Method getDefaultDataSubscriptionId = subscriptionClass.getMethod("getDefaultDataSubId");

            try {
                return ((int) getDefaultDataSubscriptionId.invoke(subscriptionManager));
            } catch (IllegalAccessException e) {
                return ERROR_CODE_EXCEPTION_HANDLED;
            } catch (InvocationTargetException e) {
                return ERROR_CODE_EXCEPTION_HANDLED;
            }
        } catch (NoSuchMethodException e) {
            return ERROR_CODE_NO_SUCH_METHOD;
        }
    } catch (ClassNotFoundException e) {
        return ERROR_CODE_EXCEPTION_HANDLED;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接