メディア・リポジトリへのアクセスを確認[Kotlin]


fun checkPermission() {
        val WRITE_PERMISSION = android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        val READ_PERMISSION = android.Manifest.permission.READ_EXTERNAL_STORAGE

        var writePermission = ContextCompat.checkSelfPermission(this, WRITE_PERMISSION)
        var readPermission = ContextCompat.checkSelfPermission(this, READ_PERMISSION)
		
        //권한이 없는 경우
        if (writePermission == PackageManager.PERMISSION_DENIED || readPermission == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(WRITE_PERMISSION, READ_PERMISSION),
                CONTENTS_PERMISSION_CODE //사용자 임의 상수 (1로 설정해줌)
            )
        } else { 
            //권한이 있는 경우 실행할 동작
            selectPhoto()
        }
    }
override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            //전달받은 requestCode가 CONTENTS_PERMISSION_CODE 인 경우
            CONTENTS_PERMISSION_CODE -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //권한을 승인했을때 실행할 동작
                    selectPhoto()
                } else {
                    //권한을 거부했을때 실행할 동작
                    Toast.makeText(applicationContext, "접근 권한이 필요합니다", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }