Android6.0以上系统动态获取权限
Posted qiangge-python
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android6.0以上系统动态获取权限相关的知识,希望对你有一定的参考价值。
动态权限的申请方法:
1、首先,需要在androidManifest.xml静态申请权限,否则无法动态申请权限:
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.动态申请
public boolean checkSelfPermission(String permission, int requestCode) { Log.i(LOG_TAG, "checkSelfPermission " + permission + " " + requestCode); if (ContextCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this,REQUESTED_PERMISSIONS,requestCode); return false; } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { Log.i(LOG_TAG, "onRequestPermissionsResult " + grantResults[0] + " " + requestCode); switch (requestCode) { case PERMISSION_REQ_ID: { if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED || grantResults[2] != PackageManager.PERMISSION_GRANTED) { showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO + "/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE); finish(); break; } //initAgoraEngineAndJoinChannel();//获取权限后要执行的代码 break; } } } public final void showLongToast(final String msg) { this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show(); } }); }
在这里onCreate中调用checkSelfPermission方法
private static final int PERMISSION_REQ_ID = 22; // permission WRITE_EXTERNAL_STORAGE is not mandatory for Agora RTC SDK, just incase if you wanna save logs to external sdcard private static final String[] REQUESTED_PERMISSIONS = {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; ... if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) && checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) && checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) { initAgoraEngineAndJoinChannel();//申请权限成功后执行的代码 }
以上是关于Android6.0以上系统动态获取权限的主要内容,如果未能解决你的问题,请参考以下文章