最近做的安卓项目需要实现录音等功能,现在的手机基本上都是安卓6.0以上,所以不可避免的要面临设置动态权限,步骤如下:
1、首先在要申请权限的界面定义全局变量的权限数组和请求状态码;
private static String[] PERMISSIONS_STORAGE = {
//存储权限
Manifest.permission.WRITE_EXTERNAL_STORAGE,
//录音权限
Manifest.permission.RECORD_AUDIO};
//请求状态码
private static int REQUEST_PERMISSION_CODE = 1;
2、在onCreate()中判断需要申请的权限;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
}
}
3、重写回调方法
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_CODE) {
for (int i = 0; i < permissions.length; i++) {
Log.i("MainActivity", "申请的权限为:" + permissions[i] + ",申请结果:" +
grantResults[i]);
}
}
}
4、最后在AndroidManifest.xml中添加权限;
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
然后就ok了
参考:https://blog.csdn.net/m0_37724690/article/details/82284984