欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android | APP动态申请权限

程序员文章站 2022-05-10 09:45:20
...

为某个应用动态申请权限,code可以这么写:

public MainActivity extends Activity {
	private final int REQUEST_EXTERNAL_STORAGE = 1; //指定的返回码
	
	@override
	public void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		
		if (getApplicationContext()).checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
			this.requestPermission(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE); //申请权限
		}
	}
	
	@override
	public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) { //申请权限结果的回调
		switch(requestCode) {
			case READ_EXTERNAL_STORAGE:
				if (grantResults == null || grantResults.length == 0) {
					finish();
					return;
				}
				
				if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					//Do something
				} else {
					finish;
				}
				break;
			default:
				super.onRequestPermissionResult(requestCode, permissions, grantResults);
				break;
		}
	}
}

 

相关标签: 权限