由于Android系统对用户权限有限制,未经授权的应用程序不能直接访问设备标识符(如IMEI)。为了解决这个问题,需要在应用程序中请求相应的权限,如READ_PHONE_STATE权限,以获取设备标识符。以下是一个示例代码片段,阐明了如何请求READ_PHONE_STATE权限:
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, Manifest.permission.READ_PHONE_STATE)) { // Show an explanation to the user asynchronously -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed; request the permission ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.READ_PHONE_STATE}, MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
// MY_PERMISSIONS_REQUEST_READ_PHONE_STATE is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else { // Permission has already been granted }
在上面的代码中,对应用程序进行了检查,看是否已获得所请求的权限,如果没有,则将向用户显示请求权限的对话框并等待用户响应。如果用户授予了权限,则可以继续使用相关的API来访问设备标识符。