安卓如何动态申请android.permission.READ_PHONE_STATE权限完整代码
时间: 2024-01-19 11:04:25 浏览: 256
以下是安卓动态申请android.permission.READ_PHONE_STATE权限的完整代码示例:
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_READ_PHONE_STATE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 检查是否已授予android.permission.READ_PHONE_STATE权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
// 已经授予了android.permission.READ_PHONE_STATE权限
String imei = getIMEI();
Toast.makeText(this, "IMEI: " + imei, Toast.LENGTH_SHORT).show();
} else {
// android.permission.READ_PHONE_STATE权限未被授予,需要请求权限
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_PHONE_STATE }, REQUEST_CODE_READ_PHONE_STATE);
}
}
private String getIMEI() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
return telephonyManager.getDeviceId();
}
return null;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CODE_READ_PHONE_STATE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户已授予android.permission.READ_PHONE_STATE权限
String imei = getIMEI();
Toast.makeText(this, "IMEI: " + imei, Toast.LENGTH_SHORT).show();
} else {
// 用户拒绝了android.permission.READ_PHONE_STATE权限
Toast.makeText(this, "需要android.permission.READ_PHONE_STATE权限才能获取IMEI号", Toast.LENGTH_SHORT).show();
}
}
}
}
```
注意,如果您的应用程序在Android 6.0以下的版本上运行,您可以在AndroidManifest.xml文件中声明android.permission.READ_PHONE_STATE权限而不需要动态请求权限。
阅读全文