增加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
动态权限判断及请求
/**
* 需要获取的权限列表
*/
private String[] permissions = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
};
/**
* 动态申请权限的请求码
*/
private static final int PERMISSION_REQUEST_CODE = 100;
/**
* 动态申请权限
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean initPermissions() {
if (!isHasPermission()) {
//动态申请权限 , 第二参数是请求吗
requestPermissions(permissions, PERMISSION_REQUEST_CODE);
return false;
}
return true;
}
/**
* 判断是否有 permissions 中的权限
*
* @return
*/
@RequiresApi(api = Build.VERSION_CODES.M)
public boolean isHasPermission() {
for (String permission : permissions) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
权限初始化
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(initPermissions()){
init();
}
}
权限请求回调
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//权限被用户同意,做相应的事情
init();
} else {
//权限被用户拒绝,做相应的事情
finish();
}
}
|