Skip to content

Commit 836eac2

Browse files
committed
fix: API 兼容性问题
1 parent 8f09991 commit 836eac2

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

app/src/main/java/com/github/nrfr/manager/CarrierConfigManager.kt

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.github.nrfr.manager
22

33
import android.content.Context
4+
import android.os.Build
45
import android.os.PersistableBundle
56
import android.telephony.CarrierConfigManager
67
import 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

Comments
 (0)