今天主要講的是在android 5.1及以上如何判斷雙卡手機(jī)中判斷當(dāng)前的流量是使用的那張卡。
(例子中的代碼會(huì)使用到j(luò)ava反射的知識(shí))
首先判斷數(shù)據(jù)流量開(kāi)關(guān)是否打開(kāi):
/**
* 判斷數(shù)據(jù)流量開(kāi)關(guān)是否打開(kāi)
* @param context
* @return
*/
public static boolean isMobileEnabled(Context context) {
try {
Method getMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");`
getMobileDataEnabledMethod.setAccessible(true);
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (Boolean) getMobileDataEnabledMethod.invoke(connectivityManager);
}catch (Exception e) {
e.printStackTrace();`
}
return true;
}
只有在已經(jīng)打開(kāi)了流量開(kāi)關(guān)的時(shí)候才會(huì)去判斷是使用的那張卡的流量,當(dāng)沒(méi)有開(kāi)啟數(shù)據(jù)流量時(shí)即不用判斷。
下邊的方法是用于獲取當(dāng)前手機(jī)有幾張可用的手機(jī)卡,獲取這些手機(jī)卡的基本信息。
public static ListgetActiveSubscriptionInfoList(Context context){
SubscriptionManager subscriptionManager=SubscriptionManager.from(context);
? List list= (List) RefInvoker.invokeMethod(subscriptionManager, SubscriptionManager.class.getName(), "getActiveSubscriptionInfoList",
? null, null);
? return list;
}
獲取到的基本信息可能如下:
*{id=1, iccId=898600772XXXXXXXXXXX simSlotIndex=0 displayName=中國(guó)移動(dòng) carrierName=中國(guó)移動(dòng) nameSource=0 iconTint=-16746133 dataRoaming=0 iconBitmap=android.graphics.Bitmap@7e8713c mcc 460 mnc 0}*
simSlotIndex是卡槽位置,通過(guò)卡槽id便可以獲取到對(duì)應(yīng)的subId,最后通過(guò)subId則可以判斷出這張卡的流量是否打開(kāi)。
獲取subId代碼如下:
int[] subId = (int[]) RefInvoker.invokeStaticMethod(SubscriptionManager.class.getName(), "getSubId", new Class[]{int.class}, new Object[]{simid});
判斷對(duì)應(yīng)手機(jī)卡的流量狀態(tài)代碼如下:
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
int type= (int) RefInvoker.invokeMethod(telephonyManager,TelephonyManager.class.getName(), "getDataNetworkType",new Class[]{int.class}, new Object[]{subId[0]});
此時(shí)如果type!=0則表示打開(kāi)的是此卡的流量。
第一次寫文章,可能寫的不太好,大家多多包涵。