我正在用Kotlin开发一个Android应用程序,我使用的是api 28。
我想获取deviceId号。一开始我使用TelephonyManager.deviceId,经过一番研究,我发现它已被弃用。
我找到解决方案,用getImei()替换deviceId
以下摘录自我的代码:
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (telephonyManager != null) {
val androidID = Settings.Secure.getString(this.contentResolver, Settings.Secure.ANDROID_ID)
if (androidID != null) {
Utility().DEVICE_ID = androidID
Utility().setDataBykeyValue(applicationContext, AppController.SHAIRD_PREF_DEVICE_ID, androidID)
} else {
val devId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) telephonyManager.getImei()
else telephonyManager.getDeviceId()
Utility().DEVICE_ID = devId
Utility().setDataBykeyValue(applicationContext, AppController.SHAIRD_PREF_DEVICE_ID, devId)
}
Utility().CARRIER = telephonyManager.simOperatorName
}
我也将此权限添加到我的AndroidManifest.xml中:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
“ telephonyManager.getImei()”用红线下划线,并显示以下消息:
呼叫需要许可,但可能会被用户拒绝:代码应 明确检查权限是否可用(带有 checkPermission)或明确处理潜在问题
我想知道问题出在哪里,我该如何解决
答案 0 :(得分:1)
对于Java:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
} else {
// else for if they have already given permission
}
}
您还可以查看本教程:https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/
对于Kotlin:
val permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 1)
}
您还可以查看本教程:https://www.techotopia.com/index.php/Kotlin_-_Making_Runtime_Permission_Requests_in_Android
答案 1 :(得分:0)
public static String getImei(TelephonyManager tm) {
String imei;
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
imei = tm.getDeviceId(0);
}else{
imei = tm.getDeviceId();
}
}catch(SecurityException e){
imei = "";
}
return imei;
}