首页  编辑  

MTK双卡双待手机下切换不同SIM卡上网

Tags: /Android/   Date Created:
安卓4.4以上系统中,MTK方案如何用代码实现切换不同的SIM来上网?

调用方法,例如使用SIM卡2上网,传入1,使用SIM卡1上网,传入0即可:
setDefaultDataSub(1);
try {
setDataEnabled(1, true, this);
} catch (Exception e) {
e.printStackTrace();
}
核心代码:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
public void setDataEnabled(int slotIdx, boolean enable, Context context) throws Exception
{
try {
int subid = SubscriptionManager.from(context).getActiveSubscriptionInfoForSimSlotIndex(slotIdx).getSubscriptionId();
TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Method setDataEnabled = telephonyService.getClass().getDeclaredMethod("setDataEnabled", int.class, boolean.class);
if (null != setDataEnabled) {
setDataEnabled.invoke(telephonyService, subid, enable);
Log.i(TAG,"setDataEnabled OK");
}
}catch (Exception e)
{
e.printStackTrace();
Log.i(TAG,"setDataEnabled error");
}
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
public void setDefaultDataSub(int slotindex)
{
SubscriptionManager sm = SubscriptionManager.from(this);
int subId = sm.getActiveSubscriptionInfoForSimSlotIndex(slotindex).getSubscriptionId();
try {
Method method = sm.getClass().getMethod("setDefaultDataSubId",int.class);
if(method != null)
{
method.invoke(sm, subId);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
上面的代码,需要系统权限才可以支持:
1. Manifest中增加请求系统账户权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.abc" android:sharedUserId="android.uid.system">
2. 增加请求权限:
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"></uses-permission>
3. 使用系统证书签名。