Android 双卡适配 subId 相关方法

业务场景

双卡设备进行网络等业务时,需要正确操作对应的卡。

执行卡业务和主要是使用subId和 PhoneId/SlotId进行区分隔离。

代码举例

初始化subId

//初始化subId
private int mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;

//1、通过intent传值(常用场景),默认为invaildId
int mSubId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
                SubscriptionManager.INVALID_SUBSCRIPTION_ID);

//2、根据注册信息subscriptionInfo
private SubscriptionInfo mSub; //接口传值初始化,认为已经非null
mSubId = mSub.getSubscriptionId();

//3、通过Phone全局常量
mSubId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, 0);

//4、根据Phone对象
int mSubId = phone.getSubId();

//5、根据卡槽获取
int mSubId = getSubId(soltId);

1、获取CarrierConfig 运营商配置

private PersistableBundle mCarrierConfig = null;
//通过subId获取CarrierConfig
CarrierConfigManager configManager = (CarrierConfigManager)
                    getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
mCarrierConfig = configManager.getConfigForSubId(mSubid);

2、获取TelephonyManager

TelephonyManager tm = (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
tm = tm.createForSubscriptionId(mSubid);  //关键点,拿到对应subId的tm
String mImsi = tm.getSubscriberId(mSubid);  //imsi?not subid?

3、获取Phone 对象

if (mSubId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
    int mPhoneId = SubscriptionManager.getPhoneId(mSubId); 
}

综合

private boolean setOperatorNetworkInfo(Context context, int slotId, int subId) {
    SubscriptionManager subscriptionManager = SubscriptionManager.from(context);
    TelephonyManager telephonyManager = TelephonyManager.from(context);
    //能直接调接口就不要调嵌套的啦,上面的TelephonyManager 初始化等同于下
    //TelephonyManager telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE);

    int mSubId = getSubId(soltId);

    if(soltId >= 0 && soltId < PHONE_COUNT){
        Phone phone = PhoneFactory.getPhone(soltId);
        SubscriptionInfo subInfo = subscriptionManager.getActiveSubscriptionInfo(subId);
        String mccmnc = telephonyManager.getSimOperator(subId);
        String imsi = telephonyManager.getSubscriberId(subId);
    }

}

//======== 相关源码类 SubscriptionManager & TelephonyManager =========
    /**
     * @deprecated developers should always obtain references directly from
     *             {@link Context#getSystemService(Class)}.
     */
    @Deprecated
    public static SubscriptionManager from(Context context) {
        return (SubscriptionManager) context
                .getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
    }

    /** {@hide} */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public static TelephonyManager from(Context context) {
        return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    }

其他相关说明

【笔记】Android Telephony | SIM 卡管理和subId、slotId、phoneId 定义关系说明-CSDN博客

你可能感兴趣的:(Android,Telephony,Telephony,APN,Data,Android,Telephony,Subscription,网络注册,移动数据网络)