android - 在 Android P 中以有效的方式获取 android.os.SystemProperties
问题描述
在 Android P 中,非 SDK 接口已被弃用。(链接:https ://developer.android.com/about/versions/pie/restrictions-non-sdk-interfaces )在我们的旧代码中,我们以下列方式使用“android.os.SystemProperties”,
String countryCode = null;
try
{
Class<?> cl;
cl = Class.forName("android.os.SystemProperties");
Method method = cl.getDeclaredMethod("get", String.class);
countryCode = (String) method.invoke(null, "ro.csc.countryiso_code");
return
}
由于我们不能再以这种方式使用它,我现在尝试通过以下方式获得相同的值,
String propertyValue = "";
BufferedReader reader = null;
Process process = Runtime.getRuntime().exec("getprop " + key);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
propertyValue = reader.readLine().trim();
虽然这是一种标准方式,但它非常慢,正如您所见,它正在创建一个新进程,然后运行 shell 命令 getprop 等等。我的问题是,有没有更好的方法来获得这些属性?
解决方案
为什么需要使用反射?
您可以像这样获取国家/地区 ISO 代码:
import android.telephony.TelephonyManager
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val iso = telephonyManager.simCountryIso
https://developer.android.com/reference/android/telephony/TelephonyManager#getSimCountryIso()
返回与 SIM 提供商的国家代码等效的 ISO-3166-1 alpha-2 国家代码。
ISO-3166-1 alpha-2 国家代码以小写 2 字符格式提供。