https://developerpearl.tistory.com/45
위 과정을 거쳐 권한 확인을 했다.
이제 권한을 요청해보자.
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
권한 요청 코드 예제
'안드로이드' 카테고리의 다른 글
[안드로이드] 2-1. WebView 웹뷰 - 로컬 HTML불러오기 (Kotlin) (0) | 2023.03.11 |
---|---|
[안드로이드] 1. WebView 웹뷰- 띄우기 (Kotlin) (0) | 2023.03.11 |
[안드로이드] Permission - 권한 확인하기(checkSelfPermission)(feat. Kotlin) (0) | 2023.01.27 |
[Kotlin] CSV 파일 읽고 쓰기 (0) | 2023.01.15 |
[안드로이드] AlertDialog : yes, no창 띄우기. 확인창 띄우기, 알림창 띄우기!(Kotlin) (1) | 2023.01.14 |
댓글