logo头像
Snippet 博客主题

Android 如何弹出获取权限对话框

转载声明:商业转载请联系作者获得授权,非商业转载请注明出处 © soho.tips


以获取sdcard写权限为例: AndroidManifest需要加入权限:

AndroidManifest
1
<uses-permission android:name="android.permission.WRITE\_EXTERNAL\_STORAGE"></uses-permission>

代码中加入:

java代码文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void requestPermission() {
//request external storage write permission
try {
int hasWriteExternalStoragePermission =this.checkSelfPermission(Manifest.permission.WRITE\_EXTERNAL\_STORAGE);//权限检查
if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String\[\] {Manifest.permission.WRITE\_EXTERNAL\_STORAGE},
Constants.EXTERNAL\_STORAGE\_PERMISSION\_REQUEST\_CODE);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "获取权限异常", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String\[\] permissions, int\[\] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == Constants.EXTERNAL\_STORAGE\_PERMISSION\_REQUEST\_CODE) {
if (grantResults\[0\] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(getApplicationContext(), "获取权限失败, 终止.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
转载声明:商业转载请联系作者获得授权,非商业转载请注明出处 © soho.tips
微信打赏

不考虑赞赏一个?