Android動態檢查並取得Camera和錄音權限


加入相依性,版本號隨著你的專案的SDK版本改變,我這裡用28
dependencies {
    implementation 'com.android.support:support-compat:28.0.0'
    implementation 'com.android.support:appcompat-v7:28.0.0'

REF: https://developer.android.com/topic/libraries/support-library/packages

引用
import android.util.Log;
import android.widget.Toast;
import android.Manifest.permission;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

你需要權限的函數
    public void yourFunction(View view) {
...
        if (!grantPermission()) return;
...
}

//自訂權限需求
    final static int MY_PERMISSIONS_REQUEST = 1001;

//檢查並取得權限
    private boolean grantPermission() {
        Log.d("PERM", "grantPermission");
        boolean hasPerm = true;
        int res;
        res = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
        if (PackageManager.PERMISSION_GRANTED != res) hasPerm = false;
        res = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
        if (PackageManager.PERMISSION_GRANTED != res) hasPerm = false;
        if (!hasPerm) {
            Log.e("PERM", "no permission");
            ActivityCompat.requestPermissions(this,
                    new String[] {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST);
        }
        return hasPerm;
    }

//Override onRequestPermissionsResult 並處理使用者回應結果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.d("PERM", "onRequestPermissionsResult");
        if (MY_PERMISSIONS_REQUEST == requestCode) {
            boolean hasPerm = true;
            if (PackageManager.PERMISSION_GRANTED != grantResults[0]) hasPerm = false;
            if (PackageManager.PERMISSION_GRANTED != grantResults[1]) hasPerm = false;
            if (hasPerm) {
                makeCall(null);
            }
            else {
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }



留言