[Android] Check Permissions

jeongsick82·2020년 11월 11일
0

안드로이드 여러가지 권한을 요청하고 처리하는 코드

  • AndroidManifest.xml
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  • 선언
    private val reuqestCodePermission = 101
    private val keyPermissionsRequestCount = "KEY_PERMISSIONS_REQUEST_COUNT"
    private val maxNumberReqeustPermissions = 4
    private val permissions = Arrays.asList(
    	Manifest.permission.READ_EXTERNAL_STORAGE,
    	Manifest.permission.WRITE_EXTERNAL_STORAGE,
    	Manifest.permission.ACCESS_FINE_LOCATION,
    	Manifest.permission.ACCESS_COARSE_LOCATION
    )
  • onCreate()

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        ...
        savedInstanceState?.let {permissionRequestCount = it.getInt(KEY_PERMISSIONS_REQUEST_COUNT, 0)}
        ...
        requestPermissions()
        ...
    }
  • 퍼미션 체크

    private fun checkAllPermissions(): Boolean {
    var hasPermissions = true
        for (permission in permissions) {
            hasPermissions = hasPermissions and isPermissionGranted(permission)
        }
    	return hasPermissions
    }
  • 퍼미션 요청

    private fun requestPermissionsIfNecessary() {
    	if (!checkAllPermissions()) {
    		if (permissionRequestCount < MAX_NUMBER_REQUEST_PERMISSIONS) {
    			permissionRequestCount += 1
    			ActivityCompat.requestPermissions(
    				this,
    				permissions.toTypedArray(),
    				REQUEST_CODE_PERMISSIONS
    			)
    		} else {
    			Toast.makeText(this,"Go to Settings",Toast.LENGTH_LONG).show()
    		}
    	}
    }
  • onSaveInstanceState()

    override fun onSaveInstanceState(outState: Bundle) {
    	super.onSaveInstanceState(outState)
    	outState.putInt(KEY_PERMISSIONS_REQUEST_COUNT, permissionRequestCount)
    }
profile
Android=Kotlin, iOS=Swift, CrossPlatform=Flutter

0개의 댓글