GitHub address: github.com/kongpf8848/…

preface

What is the Activity Result API?

Refer to the link

The Activity Result API is Google’s official recommended way for activities and fragments to get returned results. It provides components for registering results, launching results, and processing results after the system dispatts them. The introduction is as follows:

implementation 'androidx. Activity: the activity: 1.2.0 - alpha06'
implementation 'androidx. Activity: activity - KTX: 1.2.0 - alpha06'
implementation 'androidx. Fragments: fragments: 1.3.0 - alpha06'
implementation 'androidx. Fragments: fragments - KTX: 1.3.0 - alpha06'
Copy the code

There are two main components:

ActivityResultContract: Contracts that define the type of input data and the type of output data, how the data is passed and how the returned data is processed

public abstract class ActivityResultContract<I.O> {

 /** Create an intent that can be used for {@link Activity#startActivityForResult} */
    public abstract @NonNull Intent createIntent(@NonNull Context context,
            @SuppressLint("UnknownNullness") I input);

    /** Convert result obtained from {@link Activity#onActivityResult} to O */
    @SuppressLint("UnknownNullness")
    public abstract O parseResult(int resultCode, @Nullable Intent intent); . }Copy the code

Google defines a set of activityResults contracts that are commonly used

  • StartActivityForResult, used to start a new page and get the result returned
  • RequestPermission, which is used to apply for a single permission and get the result returned
  • RequestMultiplePermissions, used to apply for multiple access and obtain returns the result
  • GetContent(), which selects the content and gets the return result
  • PickContact, used to select contacts and get returned results
  • TakePicture, used to take pictures and get returned results
  • TakeVideo, used to capture the video and get the returned results

ActivityResultLauncher: a launcher that calls the launch method of ActivityResultLauncher to launch a page jump, acting as the original startActivity()

/**
 * A launcher for a previously-{@link ActivityResultCaller#registerForActivityResult prepared call}
 * to start the process of executing an {@link ActivityResultContract}.
 *
 * @param <I> type of the input required to launch
 */
public abstract class ActivityResultLauncher<I> {

    /**
     * Executes an {@link ActivityResultContract}.
     *
     * @param input the input required to execute an {@link ActivityResultContract}.
     */
    public void launch(@SuppressLint("UnknownNullness") I input) {
        launch(input, null);
    }

    /**
     * Executes an {@link ActivityResultContract}.
     *
     * @param input the input required to execute an {@link ActivityResultContract}.
     * @param options Additional options for how the Activity should be started.
     */
    public abstract void launch(@SuppressLint("UnknownNullness") I input,
            @Nullable ActivityOptionsCompat options);

    /** * Unregisters this launcher, releasing the underlying result callback, and any references * captured within it. * * You should call this if the registry may live longer than the callback registered for this * launcher. */
    @MainThread
    public abstract void unregister(a);

    /**
     * Get the {@link ActivityResultContract} that was used to create this launcher.
     *
     * @return the contract that was used to create this launcher
     */
    @NonNull
    public abstractActivityResultContract<I, ? > getContract(); }Copy the code

If we need to apply for location permission now, the old permission application method is as follows:

 val PERMISSION_REQUEST_LOCATION = 0
  ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            PERMISSION_REQUEST_LOCATION
        )
Copy the code

And then the processing and application in onRequestPermissionsResult:

 override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_LOCATION) {
            if(grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            }
        }
    }
Copy the code

Application methods based on the Activity Result API are as follows:

   registerForActivityResult(RequestPermission()){
            /** * The application result is processed here */
            Toast.makeText(this@ForResultActivity."result:${it}", Toast.LENGTH_SHORT).show()
        }.launch(Manifest.permission.ACCESS_FINE_LOCATION)
Copy the code

All of a sudden it’s a lot simpler, isn’t it, ha ha _^_

The body of the

TKPermission is a permission class library encapsulated based on AndroidX Activity Result API, which gets rid of the old tedious permission application method and makes permission application very simple and easy

Functional features

  • Simple to use, friendly call, compatible with Kotlin and Java, using Kotlin language call more acid cool
  • Based on Google’s latest Activity Result API package, minimal code, minimalist
  • You can apply for one or multiple rights at a time, basically meeting various permission application scenarios

use

implementation 'com. Making. Kongpf8848: tkpermission: 1.0.0'
Copy the code

Kotlin

  • Apply for one permission at a time
permission(Manifest.permission.CAMERA) {
    /** * callback */ if permission permits
   granted {
   }
   /** * Callback */ when permission is denied
   denied {
   }
}
Copy the code
  • Apply for multiple permissions at a time
permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO) {
     /** * Callback */ when all permissions are allowed
     allGranted {

     }
     /** * List of denied permissions */
     denied {

     }
}
Copy the code

Java

  • Apply for one permission at a time
PermissionUtils.INSTANCE.requestPermission(this, Manifest.permission.READ_PHONE_STATE, new PermissionListener() {
    /** * callback */ if permission permits
    @Override
    public void granted(String permission) {}/** * Callback */ when permission is denied
    @Override
    public void denied(String permission) {}});Copy the code
  • Apply for multiple permissions at a time

    PermissionUtils.INSTANCE.requestMultiplePermissions(this, Arrays.asList(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS), new MultiplePermissionsListener() {
        /** * Callback */ when all permissions are allowed
        @Override
        public void allGranted(a) {}/** * List of denied permissions */
        @Override
        public void denied(List<String> list) {}});Copy the code

Hope TKPermission can help students in need, wish everyone a smooth work, happy every day!

GitHub address: github.com/kongpf8848/…