1. 程式人生 > 其它 >android 動態許可權管理

android 動態許可權管理

在主activity中寫回調
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: //Toast.makeText(this, "許可權", Toast.LENGTH_SHORT).show(); break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); break; } }


單獨寫一個方法
`public class PermissionApply {
Context context;

public PermissionApply(Context context) {
    this.context = context;

}
//在SD卡中建立與刪除檔案許可權
String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//沒有申請到的許可權
List<String> mPermissionList = new ArrayList<>();
// 檢查許可權
public void checkPermission() {
    mPermissionList.clear();
    //判斷哪些許可權未授予
    for (int i = 0; i < permissions.length; i++) {
        if (ContextCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
            mPermissionList.add(permissions[i]);
        }
    }
    /**
     * 判斷是否為空
     */
    if (mPermissionList.isEmpty()) {//未授予的許可權為空,表示都授予了

    } else {//請求許可權方法
        String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//將List轉為陣列
        ActivityCompat.requestPermissions((Activity) context, permissions, 1);
    }
}

}
`