iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐙

No More Hassle with Android Permissions: Using ActivityResultContracts

に公開

This is a revised and updated version of my article originally posted on Note.

Using ActivityResultContracts, added in Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02, makes the process of handling onActivityResult more readable. It also simplifies the process of requesting permissions, which I will introduce here.

Official Documentation

Define required permissions in Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sobaya.example.allflow">

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

In this example, we are requesting location permissions.

Requesting permissions in Activity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
            test()
        } else {
            println("Already have permission")
        }
    }

    fun test() {
        val rp = ActivityResultContracts.RequestPermission()
        val getContent = registerForActivityResult(rp) {
            if (it) {
                println("Permission granted")
            } else {
                println("Permission denied")
            }
        }
        getContent.launch(Manifest.permission.ACCESS_FINE_LOCATION)
    }

Explanation

ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED

Here, it first checks whether the permission is already granted. If the permission is not held, it calls the test method.

Inside the test method, as you can see, it prepares for the permission request, sets up the process for when onActivityResult is received, and then executes the permission request.

Execution Results

I/System.out: Permission granted
I/System.out: Already have permission

Sample Code

https://github.com/sobaya-0141/AllFlow/tree/use_ActivityResultContracts

Discussion