动态获取权限
2019-5-8 liuyingcong 安卓开发
以录音为例,演示一下Android中动态获取权限的过程:
首先在 AndroidManifest.xml 配置文件中添加权限请求:
<uses-permission android:name="android.permission.RECORD_AUDIO"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>下面是动态获取权限的代码:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 以录音为例,演示动态获取权限的过程 // 当想要录音时,直接调用 checkPermission() 即可。如果已经有权限了,则直接去录音;如果没有,则去获取。 checkPermission(); } // 检查是否有权限 private void checkPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // 已经有权限了,直接去录音 record(); } else { // 还没获取权限,去获取 String[] permissions = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE}; ActivityCompat.requestPermissions(this, permissions, 100); } } // 获取权限的结果 @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 100) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { // 获取了两个权限,去录音 record(); } else { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO) && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // 拒绝了 Toast.makeText(this, "需要开启录音和存储权限,请重试", Toast.LENGTH_SHORT).show(); } else { // 用户选择了拒绝后不再弹出 showDialog(); } } } } // 提示用户去设置中开启权限 private void showDialog() { new AlertDialog.Builder(this) .setTitle("未获取权限") .setMessage("需要去设置中开启录音和存储权限") .setPositiveButton("去开启", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 200); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } // 去设置中开启权限的回调 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 200) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // 获取到权限了,去录音 record(); } else { // 没获取到权限,提示 Toast.makeText(this, "请去设置中打开本应用的录音和存储权限", Toast.LENGTH_SHORT).show(); } } } private void record() { // 录音的代码 } }