2019年5月25日土曜日

android開発 permission取得

2019 May 25.

"AndroidManifest.xml"
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xxx.xxx.sampletakephotogetimagefile">
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>



if(Build.VERSION.SDK_INT >= 23){
            checkPermission();
}
PROCESS_AFTER_GETTING_PERMISSIONS


// Permissionの確認
//   reuse of https://akira-watson.com/android/mediastore.html
@TargetApi(Build.VERSION_CODES.M)
public void checkPermission() {
    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
        requestCameraPermission();
    }
    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
        requestExStoragePermission();
    }
}

// CameraPermission許可を求める
@TargetApi(Build.VERSION_CODES.M)
private void requestCameraPermission() {
    if (shouldShowRequestPermissionRationale( Manifest.permission.CAMERA)) {
        requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);

    } else {
        Toast toast = Toast.makeText(this, "許可されないとアプリが実行できません", Toast.LENGTH_SHORT);
        toast.show();
        requestPermissions(new String[]{Manifest.permission.CAMERA }, REQUEST_PERMISSION_CAMERA);
    }
}

// ExternalStoragePermission許可を求める
@TargetApi(Build.VERSION_CODES.M)
private void requestExStoragePermission() {
    if (shouldShowRequestPermissionRationale( Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION__EX_STORAGE);

    } else {
        Toast toast = Toast.makeText(this, "許可されないとアプリが実行できません", Toast.LENGTH_SHORT);
        toast.show();
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE }, REQUEST_PERMISSION__EX_STORAGE);
    }
}


// requestPermission結果に対する処理
@Override
public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQUEST_PERMISSION_CAMERA) {
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            // 拒否された時の対応
            Toast toast = Toast.makeText(this, "これ以上なにもできません", Toast.LENGTH_SHORT);
            toast.show();
        }
    } else if (requestCode == REQUEST_PERMISSION__EX_STORAGE) {
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            // 拒否された時の対応
            Toast toast = Toast.makeText(this, "これ以上なにもできません", Toast.LENGTH_SHORT);
            toast.show();
        }
    } else {
        Toast toast = Toast.makeText(this, "Bad requestCode", Toast.LENGTH_SHORT);
        toast.show();
    }
}

0 件のコメント:

コメントを投稿