본문 바로가기

OS/Android

안드로이드 권한 요청

반응형
class MainActivity : AppCompatActivity()
{
    val arr_permission = listOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
    val HAHA_FOLDER_NAME = "/Download/HAHA/"

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if(checkPermission())
        {
            makeHAHADATAFolder()
        }
    }

    fun checkPermission() : Boolean
    {
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        {
            return true
        }

        var nCheck = 0
        for(permission in arr_permission)
        {
            var chk = checkCallingOrSelfPermission(permission)
            if(chk == PackageManager.PERMISSION_GRANTED)
            {
                nCheck++
            }
        }

        if(nCheck == arr_permission.size)
        {
            return true
        }

        for(permission in arr_permission)
        {
            var chk = checkCallingOrSelfPermission(permission)
            if(chk == PackageManager.PERMISSION_DENIED)
            {
                requestPermissions(arr_permission.toTypedArray(), 0)
            }
        }
        return false
    }

    fun makeHAHADATAFolder()
    {
        var f = File(Environment.getExternalStorageDirectory(), HAHA_FOLDER_NAME)
        if(!f.exists())
        {
            f.mkdir()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == 0)
        {
            var sizeResult = 0
            for(result in grantResults)
            {
                if(result == PackageManager.PERMISSION_GRANTED)
                {
                    sizeResult++
                }
            }

            if(sizeResult == grantResults.size)
            {
                Toast.makeText(this,  "권한 모두 승인했음", Toast.LENGTH_SHORT).show()
                makeZERODATAFolder()
            }
            else
            {
                Toast.makeText(this,  "거부한 권한이 있음", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

 

api 23 이상일 때만 checkPermission() 함수가 실행되므로 manifest에도 permission을 추가해야함!

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

반응형