我能够确定我的设备是使用Wifi还是移动数据。现在,我一直在识别SIM卡运营商,以便在双卡设备的情况下提供移动数据。
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if(ni.getDetailedState().toString().toLowerCase().equals("connected")){
tv.setText(" Typename: "+ni.getTypeName());
tv.append("\n Detailed state: "+ni.getDetailedState()+"\n Extra Info: "+ni.getExtraInfo()+"\n Type: "+ni.getType()+"\n Reason :"+ni.getReason()
+"\n SubType Name :"+ni.getSubtypeName()+"\n SubType :"+ni.getSubtype()+"\n State :"+ni.getState());
if(!ni.getTypeName().toString().toLowerCase().equals("wifi")){
tv.append("\n Carrier:"+carrierName);
}
}
}
以上代码标识WIFI和数据。但是,如果设备使用移动数据,并且如果它是双SIM卡设备,我如何识别哪个SIM卡正在提供移动数据?enter code here
答案 0 :(得分:0)
对于API> = 21
来自Settings.Global
int sim = -1;
SubscriptionManager sm = (SubscriptionManager)context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
if (sm != null) {
try {
int id = Settings.Global.getInt(context.getContentResolver(), "multi_sim_data_call");
SubscriptionInfo si = sm.getActiveSubscriptionInfo(id);
if (si != null)
sim = si.getSimSlotIndex();
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
}
或使用反射
int sim = -1;
SubscriptionManager sm = (SubscriptionManager)context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
if (sm != null) {
try {
Method mGetDefaultDataSubId = getMethod(sm.getClass(), "getDefaultDataSubscriptionId", 0);
if (mGetDefaultDataSubId != null) {
int id = (int) mGetDefaultDataSubId.invoke(sm);
SubscriptionInfo si = sm.getActiveSubscriptionInfo(id);
if (si != null)
sim = si.getSimSlotIndex();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Method getMethod (Class c, String name, int params) {
Method[] cm = c.getDeclaredMethods();
for (Method m : cm) {
if (m.getName().equalsIgnoreCase(name)) {
m.setAccessible(true);
int length = m.getParameterTypes().length;
if (length == params)
return m;
}
}
return null;
}