안드로이드

[안드로이드] Permission - 권한 허용 요청(requestPermissions)(feat. Kotlin)

디벨로펄 2023. 1. 27.
반응형

https://developerpearl.tistory.com/45

 

[안드로이드] Permission - 권한 확인하기(checkSelfPermission)(feat. Kotlin)

차근차근 가보자. 특정 기능을 실행시키기 위한 권한을 사용자가 이미 허용했는지 안했는지확인하는 방법에 대해서 알아보자. (본 단계 진행을 위해서는 Manifest에 권하는 권한에 대해 추가를 해

developerpearl.tistory.com

위 과정을 거쳐 권한 확인을 했다. 

이제 권한을 요청해보자.

 

requestPermissions
public static void requestPermissions(
    @NonNull Activity activity,
    @NonNull String[] permissions,
    @IntRange(from = 0) int requestCode
)

요청하는 permission들은 manifest에 선언되어 있어야하며, 현재 앱에서 허용되어있지 않으며, protection level이 위험(dangerous)이어야 한다. 

* PROTECTION_NORMAL은 설치 시에 허용된다. PROTECTION_SIGNATURE도 비슷.

 

- 단일 권한 요청 : RequestPermission

- 여러 권한 동시 요청 : RequestMultiplePermissions

// Register the permissions callback, which handles the user's response to the
// system permissions dialog. Save the return value, an instance of
// ActivityResultLauncher. You can use either a val, as shown in this snippet,
// or a lateinit var in your onAttach() or onCreate() method.

// 퍼미션 콜백 등록. 권한 다이얼로그에 대한 유저의 반응을 다룬다. 
// 결과인 isGranted를 아래와 같이 쓰거나, onAttach(), OnCreate()에서 lateinit var에 설정하거나.
// 얘는 mainactivity 또는 프래그먼트의 oncreate이전에 생성되어 있어야하므로, oncreate밖에 선언한다.
val requestPermissionLauncher =
    registerForActivityResult(RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
        	// 퍼미션 허용햇을때 action -> action 진행 or 워크 플로우 진행
        } else {
            // Explain to the user that the feature is unavailable because the
            // feature requires a permission that the user has denied. At the
            // same time, respect the user's decision. Don't link to system
            // settings in an effort to convince the user to change their
            // decision.
        }
    }

- Test를 위해서 아래 코드를 직접 실행해보도록 한다.(현재 권한이 없는 경우에만 가능.)

requestPermissionLauncher.launch(
                Manifest.permission.READ_IMAGES_PERMISSION)

위 코드의 실행결과.

※ WRITE_EXTERNAL_STORAGE

- 해당 권한은 API 19이후부터 Context.getExternalFilesDir(String) and Context.getExternalCacheDir() 두 메서드에 의해 리턴되는 directory에 있는 파일을 읽거나 쓸 때 필요하지 않다.

-----> launch해도 사용자에게 물어보는 창이 뜨지 않는다는 사실 인식하자.(이거 때메 시간 날렸네... 내 20분..)

- 19 이전의 경우는 필요함.

 

※ Manifest.permission.READ_IMAGES_PERMISSION

- 해당 권한은 사진, 동영상 엑세스 허용 퍼미션이다. API 33이후부터 사용가능(티라미수)

 

shouldShowRequestPermissionRationale
public static boolean shouldShowRequestPermissionRationale(
    @NonNull Activity activity,
    @NonNull String permission
)

함수명에서도 알 수 있듯이 요청 퍼미션에 대한 설명을 보여주어야 하는가?에 대한 답을 return한다.

(함수 이름은 길어도 무슨 역할을 하는지 알 수 있도록 작성하는게 좋겠다. ㅇ.ㅇ)

요청하는 permission에 대한 설명이 필요한지 아닌지 여부를 리턴한다.

CASE 분석

1. 설치 시 권한 허용 전에 호출 시 : false

2. 허용 안함-> 누르고 다시 호출 시 : true

3. 허용 안함 2번 이상 누를 시 : false

4. 이후 수동으로 허용하고, 다시 허용 안함으로 바꿨을 경우 : true

권한 요청 코드 예제

 

반응형

댓글