我在写一个网络监控应用。我想要检测双卡手机中哪一张SIM卡开启了数据?
我已经为两张SIM卡尝试了TelephonyManager.isDataEnabled()方法。但是该方法返回两个SIMs的enabled。相反,我应该对一张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,表示在两个SIMs上都启用了数据。这显然是不正确的,我只希望一张SIM卡为1,另一张SIM卡为0。
发布于 2020-07-17 22:35:38
可以在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;
}
}https://stackoverflow.com/questions/57504598
复制相似问题