How to check permission in fragment

前端 未结 9 1942
执念已碎
执念已碎 2020-12-01 03:49

I want to check a permission inside a fragment.

my code:

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPe         


        
9条回答
  •  萌比男神i
    2020-12-01 04:38

    I was getting tripped up using checkSelfPermission() in a Fragment and wondering what would be the best approach for Context being null (Kotlin specific)... should I use !! or something else?

    I went with something else based on code I found in iosched. Have a look at the sample below, and remember, before the Fragment is attached to an Activity, the Context will be null.

    private fun fineLocationPermissionApproved(): Boolean {
    
        val context = context ?: return false
    
        return PackageManager.PERMISSION_GRANTED == checkSelfPermission(
            context,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    }
    

提交回复
热议问题