首頁 > 軟體

Android申請相機許可權和讀寫許可權範例

2022-02-11 19:07:01

開發一個相機應用,需要申請三個許可權:相機、讀檔案、寫檔案。

1、在AndroidManifest.xml中新增

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2、新建一個Permission類

public class Permission {
    public static final int REQUEST_CODE = 5;
    //定義三個許可權
    private static final String[] permission = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    //每個許可權是否已授
    public static boolean isPermissionGranted(Activity activity){
        if(Build.VERSION.SDK_INT >= 23){
            for(int i = 0; i < permission.length;i++) {  
                int checkPermission = ContextCompat.checkSelfPermission(activity,permission[i]);
                /***
                 * checkPermission返回兩個值
                 * 有許可權: PackageManager.PERMISSION_GRANTED
                 * 無許可權: PackageManager.PERMISSION_DENIED
                 */
                if(checkPermission != PackageManager.PERMISSION_GRANTED){
                    return false;
                }
            }
            return true;
        }else{
            return true;
        }
    }

    public static boolean checkPermission(Activity activity){
        if(isPermissionGranted(activity)) {
            return true;
        } else {
            //如果沒有設定過許可權許可,則彈出系統的授權視窗
            ActivityCompat.requestPermissions(activity,permission,REQUEST_CODE);
            return false;
        }
    }
}

3、在MainActivity中加入授權操作

@Override
    protected void onStart() {
        super.onStart();
        Permission.checkPermission(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(Permission.isPermissionGranted(this)) {
            Log.i("PERMISSION","請求許可權成功");
        }
    }

初步授權成功

4、在MainActivity中處理授權失敗結果,拒絕授權則退出應用

    @Override
    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Permission.REQUEST_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Log.e("Permission","授權失敗!");
                    // 授權失敗,退出應用
                    this.finish();
                    return;
                }
            }
        }
    }

效果圖

到此這篇關於Android申請相機許可權和讀寫許可權範例的文章就介紹到這了,更多相關Android申請相機許可權內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com