11package com.github.nrfr.manager
22
33import android.content.Context
4+ import android.os.Build
45import android.os.PersistableBundle
56import android.telephony.CarrierConfigManager
67import android.telephony.SubscriptionManager
@@ -63,7 +64,24 @@ object CarrierConfigManager {
6364 private fun getCarrierNameBySubId (context : Context , subId : Int ): String {
6465 val telephonyManager = context.getSystemService(Context .TELEPHONY_SERVICE ) as ? TelephonyManager
6566 ? : return " "
66- return telephonyManager.getNetworkOperatorName(subId)
67+
68+ return try {
69+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .Q ) {
70+ // Android 10 及以上使用新 API
71+ telephonyManager.getNetworkOperatorName(subId)
72+ } else {
73+ // Android 8-9 使用反射获取运营商名称
74+ val createForSubscriptionId = TelephonyManager ::class .java.getMethod(
75+ " createForSubscriptionId" ,
76+ Int ::class .javaPrimitiveType
77+ )
78+ val subTelephonyManager = createForSubscriptionId.invoke(telephonyManager, subId) as TelephonyManager
79+ subTelephonyManager.networkOperatorName
80+ }
81+ } catch (e: Exception ) {
82+ // 如果获取失败,回退到默认的 TelephonyManager
83+ telephonyManager.networkOperatorName
84+ }
6785 }
6886
6987 fun setCarrierConfig (subId : Int , countryCode : String? , carrierName : String? = null) {
@@ -101,4 +119,4 @@ object CarrierConfigManager {
101119 )
102120 carrierConfigLoader.overrideConfig(subId, bundle, true )
103121 }
104- }
122+ }
0 commit comments