Android 10 5G 双卡 获取当前网络 基站ID

2021-09-16  本文已影响0人  kalshen

其实这个需求很少用,查到的资料一般比较老,基本上没办法稳定获取到cellInfo

通过搜索github requestCellInfoUpdate , 得到一些较新的网络库中,对android10 进行了适配

private fun getAllCellInfo() {
        val tm: TelephonyManager =
            getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val sm =
            getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
        //此处处理为了适配 android 10 ,不处理则 allCellInfo = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //需要请求更新cellInfo
            tm.requestCellInfoUpdate({ command ->
                val mainHandler = Handler(requireContext().mainLooper)
                mainHandler.post(command)
            }, object : TelephonyManager.CellInfoCallback() {
                override fun onCellInfo(cellInfo: MutableList<CellInfo>) {
                    handlerAllCellInfo(sm, cellInfo)
                }
            })
        } else {
            handlerAllCellInfo(sm, tm.allCellInfo)
        }

    }
 private fun handlerAllCellInfo(
        sm: SubscriptionManager,
        cellInfo: MutableList<CellInfo>
    ) {
        //获取当前选择的默认卡
        val subId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            SubscriptionManager.getDefaultDataSubscriptionId()
        } else {
            SmsManager.getDefaultSmsSubscriptionId()
        }
        val index =
            sm.activeSubscriptionInfoList.firstOrNull { it.subscriptionId == subId }?.simSlotIndex
                ?: 0
        val info = cellInfo.filter { it.isRegistered }.getOrNull(index)
        var cellId = -1L
        if (info is CellInfoGsm) {
            info.cellIdentity.cid.let {
                it > 0
                cellId = it.toLong()
            }
        } else if (info is CellInfoCdma) {
            info.cellIdentity.basestationId.let {
                it > 0
                cellId = it.toLong()
            }
        } else if (info is CellInfoLte) {
            info.cellIdentity.ci.let {
                it > 0
                cellId = it.toLong()
            }
        } else if (info is CellInfoWcdma) {
            info.cellIdentity.cid.let {
                it > 0
                cellId = it.toLong()
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && info is CellInfoNr) {
                (info.cellIdentity as CellIdentityNr).nci.let {
                    it > 0
                    cellId = it
                }
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读