You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android R以下如何获取getPhoneCount()并判断设备是否支持双卡

解答

关于Android R以下版本的实现方案

  • 你当前的版本分支判断逻辑是合理的。getPhoneCount 仅在Android 11(API 30,即版本R)才被官方标记废弃,在API 23到API 29的范围内,这是官方提供的唯一公开可用的查询卡槽数量的API,没有其他非废弃的公开替代接口可以使用。
  • 如果你需要兼容Android 6.0(API 23)以下的版本,可以通过反射调用TelephonyManager的隐藏方法getPhoneCount,或者读取系统属性ro.telephony.multi_sim、ro.multi_sim.support等参数判断,不过这些隐藏方法和系统属性不保证所有厂商设备都兼容,可能存在适配问题。

关于是否需要添加废弃警告压制注解

  • 需要添加@SuppressWarnings("deprecation")注解。你已经通过版本判断做了隔离,只有API低于30的设备才会走到调用getPhoneCount的分支,不会在高版本系统中触发废弃API的调用风险,添加该注解只会消除编译期的警告,不会带来任何运行时隐患。

补充注意事项

  • 调用getActiveModemCount和getPhoneCount都需要申请READ_PHONE_STATE权限,如果你的应用targetSdkVersion >= 33,还需要额外申请READ_BASIC_PHONE_STATE权限,否则会抛出安全异常。
  • 注意这两个接口返回的是当前激活的调制解调器数量,不是设备硬件支持的最大卡槽数:部分双卡设备如果用户只插入了一张SIM卡,接口会返回1,如果你需要判断设备硬件是否支持双卡,需要额外适配厂商的定制逻辑。
  • 你原方法名isDuelSim存在拼写错误,正确拼写应为isDualSim。

优化后的代码示例

@SuppressWarnings("deprecation")
public boolean isDualSim(Context pContext) {
    // 先检查权限,避免抛出异常
    if (ContextCompat.checkSelfPermission(pContext, Manifest.permission.READ_PHONE_STATE) 
        != PackageManager.PERMISSION_GRANTED) {
        // 没有权限时可以根据业务逻辑返回默认值,或者先申请权限
        return false;
    }
    TelephonyManager telephony = (TelephonyManager) pContext.getSystemService(Context.TELEPHONY_SERVICE);
    if (telephony != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return telephony.getActiveModemCount() >= 2; 
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return telephony.getPhoneCount() >= 2;
        } else {
            // API23以下的兼容逻辑,可选
            try {
                Method getPhoneCountMethod = TelephonyManager.class.getDeclaredMethod("getPhoneCount");
                getPhoneCountMethod.setAccessible(true);
                int count = (int) getPhoneCountMethod.invoke(telephony);
                return count >= 2;
            } catch (Exception e) {
                // 反射失败时可以尝试读取系统属性判断
                try {
                    Class<?> systemProperties = Class.forName("android.os.SystemProperties");
                    Method getMethod = systemProperties.getMethod("get", String.class);
                    String multiSimSupport = (String) getMethod.invoke(null, "ro.telephony.multi_sim");
                    return "1".equals(multiSimSupport) || "2".equals(multiSimSupport);
                } catch (Exception ex) {
                    return false;
                }
            }
        }
    }
    return false;
}

内容的提问来源于stack exchange,提问作者Vijayadhas Chandrasekaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:36:02