├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── themes.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── xml
│ │ │ │ ├── file_paths.xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_second.xml
│ │ │ │ └── activity_main.xml
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── cn
│ │ │ │ └── hx
│ │ │ │ └── activityresultapi
│ │ │ │ ├── BaseApplication.kt
│ │ │ │ ├── BaseFragment.kt
│ │ │ │ ├── BaseActivity.kt
│ │ │ │ ├── SecondActivity.kt
│ │ │ │ ├── CustomActivityResultRegistry.kt
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ ├── resources
│ │ │ └── robolectric.properties
│ │ └── java
│ │ │ └── cn
│ │ │ └── hx
│ │ │ └── activityresultapi
│ │ │ ├── BaseFragmentTest.kt
│ │ │ └── BaseActivityTest.kt
│ ├── debug
│ │ ├── AndroidManifest.xml
│ │ ├── res
│ │ │ └── layout
│ │ │ │ └── activity_test.xml
│ │ └── java
│ │ │ └── cn
│ │ │ └── hx
│ │ │ └── activityresultapi
│ │ │ ├── TestFragment.kt
│ │ │ └── TestActivity.kt
│ └── androidTest
│ │ └── java
│ │ └── cn
│ │ └── hx
│ │ └── activityresultapi
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── library
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── cn
│ │ │ └── hx
│ │ │ └── ara
│ │ │ ├── TakeVideoCallback.java
│ │ │ ├── TakePictureCallback.java
│ │ │ ├── ActivityResultCallback.java
│ │ │ ├── RequestPermissionCallback.java
│ │ │ ├── RequestMultiplePermissionsCallback.java
│ │ │ ├── TakeVideoInfo.java
│ │ │ ├── TakePictureInfo.java
│ │ │ ├── RequestPermissionInfo.java
│ │ │ ├── TakeVideoResultInfo.java
│ │ │ ├── RequestMultiplePermissionsInfo.java
│ │ │ ├── TakePictureResultInfo.java
│ │ │ ├── StartActivityResultInfo.java
│ │ │ ├── VideoConfig.java
│ │ │ ├── RequestPermissionResultInfo.java
│ │ │ ├── StartActivityInfo.java
│ │ │ ├── ActivityResultInfo.java
│ │ │ ├── RequestMultiplePermissionsResultInfo.java
│ │ │ ├── CustomCaptureVideo.java
│ │ │ ├── ActivityResultSource.java
│ │ │ ├── ActivityResultSourceImpl.java
│ │ │ ├── ActivityResultManager.java
│ │ │ └── ActivityResultSourceDelegate.java
│ ├── test
│ │ └── java
│ │ │ └── cn
│ │ │ └── hx
│ │ │ └── ara
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── cn
│ │ └── hx
│ │ └── ara
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
├── gradle.properties
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/library/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ActivityResultApi
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/test/resources/robolectric.properties:
--------------------------------------------------------------------------------
1 | sdk=31
2 | qualifiers=w360dp-h720dp-xxhdpi
3 | instrumentedPackages=androidx.loader.content
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qq549631030/ActivityResultApi/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/TakeVideoCallback.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public interface TakeVideoCallback {
6 | void onTakeVideoResult(@NonNull TakeVideoResultInfo resultInfo);
7 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/TakePictureCallback.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public interface TakePictureCallback {
6 | void onTakePictureResult(@NonNull TakePictureResultInfo resultInfo);
7 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
9 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/ActivityResultCallback.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public interface ActivityResultCallback {
6 | void onActivityResult(@NonNull StartActivityResultInfo startActivityResultInfo);
7 | }
8 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/RequestPermissionCallback.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public interface RequestPermissionCallback {
6 | void onRequestPermissionResult(@NonNull RequestPermissionResultInfo resultInfo);
7 | }
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri May 13 09:17:16 CST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/RequestMultiplePermissionsCallback.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public interface RequestMultiplePermissionsCallback {
6 | void onRequestMultiplePermissionsResult(@NonNull RequestMultiplePermissionsResultInfo resultInfo);
7 | }
8 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/hx/activityresultapi/BaseApplication.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.app.Application
4 | import cn.hx.ara.ActivityResultManager
5 |
6 | class BaseApplication : Application() {
7 | override fun onCreate() {
8 | super.onCreate()
9 | ActivityResultManager.init(this)
10 | }
11 | }
--------------------------------------------------------------------------------
/app/src/main/java/cn/hx/activityresultapi/BaseFragment.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import androidx.fragment.app.Fragment
4 | import cn.hx.ara.ActivityResultSource
5 | import cn.hx.ara.ActivityResultSourceImpl
6 |
7 | open class BaseFragment : Fragment(), ActivityResultSource by ActivityResultSourceImpl() {
8 |
9 | val TAG = this::class.java.simpleName
10 | }
--------------------------------------------------------------------------------
/app/src/main/java/cn/hx/activityresultapi/BaseActivity.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import androidx.appcompat.app.AppCompatActivity
4 | import cn.hx.ara.ActivityResultSource
5 | import cn.hx.ara.ActivityResultSourceImpl
6 |
7 | open class BaseActivity : AppCompatActivity(), ActivityResultSource by ActivityResultSourceImpl() {
8 |
9 | val TAG = this::class.java.simpleName
10 |
11 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "ActivityResultApi"
16 | include ':app'
17 | include ':library'
18 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/TakeVideoInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public class TakeVideoInfo {
6 |
7 | @NonNull
8 | final VideoConfig config;
9 |
10 | @NonNull
11 | final TakeVideoCallback callback;
12 |
13 | public TakeVideoInfo(@NonNull VideoConfig config, @NonNull TakeVideoCallback callback) {
14 | this.config = config;
15 | this.callback = callback;
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/debug/res/layout/activity_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
--------------------------------------------------------------------------------
/library/src/test/java/cn/hx/ara/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/TakePictureInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.net.Uri;
4 |
5 | import androidx.annotation.NonNull;
6 |
7 | public class TakePictureInfo {
8 | @NonNull
9 | final Uri outputUri;
10 |
11 | @NonNull
12 | final TakePictureCallback callback;
13 |
14 | public TakePictureInfo(@NonNull Uri outputUri, @NonNull TakePictureCallback callback) {
15 | this.outputUri = outputUri;
16 | this.callback = callback;
17 | }
18 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_second.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/RequestPermissionInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public class RequestPermissionInfo {
6 |
7 | @NonNull
8 | final String permission;
9 |
10 | @NonNull
11 | final RequestPermissionCallback callback;
12 |
13 | public RequestPermissionInfo(@NonNull String permission, @NonNull RequestPermissionCallback callback) {
14 | this.permission = permission;
15 | this.callback = callback;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/TakeVideoResultInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.net.Uri;
4 |
5 | import androidx.annotation.NonNull;
6 |
7 | public class TakeVideoResultInfo extends ActivityResultInfo {
8 |
9 | public final boolean success;
10 |
11 | @NonNull
12 | public final Uri outputUri;
13 |
14 | public TakeVideoResultInfo(@NonNull String sourceUuid, boolean success, @NonNull Uri outputUri) {
15 | super(sourceUuid);
16 | this.success = success;
17 | this.outputUri = outputUri;
18 | }
19 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/RequestMultiplePermissionsInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public class RequestMultiplePermissionsInfo {
6 |
7 | @NonNull
8 | final String[] permissions;
9 |
10 | @NonNull
11 | final RequestMultiplePermissionsCallback callback;
12 |
13 | public RequestMultiplePermissionsInfo(@NonNull String[] permissions, @NonNull RequestMultiplePermissionsCallback callback) {
14 | this.permissions = permissions;
15 | this.callback = callback;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/TakePictureResultInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.net.Uri;
4 |
5 | import androidx.annotation.NonNull;
6 |
7 | public class TakePictureResultInfo extends ActivityResultInfo {
8 |
9 | public final boolean success;
10 |
11 | @NonNull
12 | public final Uri outputUri;
13 |
14 | public TakePictureResultInfo(@NonNull String sourceUuid, boolean success, @NonNull Uri outputUri) {
15 | super(sourceUuid);
16 | this.success = success;
17 | this.outputUri = outputUri;
18 | }
19 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/hx/activityresultapi/SecondActivity.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import cn.hx.activityresultapi.databinding.ActivitySecondBinding
6 |
7 | class SecondActivity : BaseActivity() {
8 | private lateinit var binding: ActivitySecondBinding
9 | override fun onCreate(savedInstanceState: Bundle?) {
10 | super.onCreate(savedInstanceState)
11 | binding = ActivitySecondBinding.inflate(layoutInflater)
12 | setContentView(binding.root)
13 | binding.btnSuccess.setOnClickListener {
14 | setResult(Activity.RESULT_OK)
15 | finish()
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/StartActivityResultInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.content.Intent;
4 |
5 | import androidx.annotation.NonNull;
6 | import androidx.annotation.Nullable;
7 |
8 | public class StartActivityResultInfo extends ActivityResultInfo {
9 | public final int resultCode;
10 | @Nullable
11 | public final Intent data;
12 | @NonNull
13 | public final Intent startIntent;
14 |
15 | public StartActivityResultInfo(@NonNull String sourceUuid, int resultCode, @Nullable Intent data, @NonNull Intent startIntent) {
16 | super(sourceUuid);
17 | this.resultCode = resultCode;
18 | this.data = data;
19 | this.startIntent = startIntent;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/VideoConfig.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.net.Uri;
4 |
5 | import androidx.annotation.NonNull;
6 |
7 | public class VideoConfig {
8 | @NonNull
9 | final Uri outputUri;
10 |
11 | public int quality = 1;
12 | public int durationLimit = 0;
13 | public long sizeLimit = 0L;
14 |
15 | public VideoConfig(@NonNull Uri outputUri) {
16 | this.outputUri = outputUri;
17 | }
18 |
19 | public VideoConfig(@NonNull Uri outputUri, int quality, int durationLimit, long sizeLimit) {
20 | this.outputUri = outputUri;
21 | this.quality = quality;
22 | this.durationLimit = durationLimit;
23 | this.sizeLimit = sizeLimit;
24 | }
25 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/RequestPermissionResultInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | public class RequestPermissionResultInfo extends ActivityResultInfo {
6 |
7 | @NonNull
8 | public final String permission;
9 |
10 | @NonNull
11 | public final Boolean grantState;
12 |
13 | @NonNull
14 | public final Boolean shouldRationale;
15 |
16 | public RequestPermissionResultInfo(@NonNull String sourceUuid, @NonNull String permission, @NonNull Boolean grantState, @NonNull Boolean shouldRationale) {
17 | super(sourceUuid);
18 | this.permission = permission;
19 | this.grantState = grantState;
20 | this.shouldRationale = shouldRationale;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/StartActivityInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.content.Intent;
4 |
5 | import androidx.annotation.NonNull;
6 | import androidx.annotation.Nullable;
7 | import androidx.core.app.ActivityOptionsCompat;
8 |
9 | public class StartActivityInfo {
10 | @NonNull
11 | final Intent intent;
12 | @Nullable
13 | final ActivityOptionsCompat optionsCompat;
14 | @NonNull
15 | final ActivityResultCallback callback;
16 |
17 | public StartActivityInfo(@NonNull Intent intent, @Nullable ActivityOptionsCompat optionsCompat, @NonNull ActivityResultCallback callback) {
18 | this.intent = intent;
19 | this.optionsCompat = optionsCompat;
20 | this.callback = callback;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/debug/java/cn/hx/activityresultapi/TestFragment.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.os.Bundle
4 | import androidx.activity.result.ActivityResultRegistry
5 |
6 | class TestFragment : BaseFragment() {
7 |
8 | val registry = CustomActivityResultRegistry()
9 |
10 | override fun customRegistry(): ActivityResultRegistry? {
11 | return registry
12 | }
13 |
14 | override fun onCreate(savedInstanceState: Bundle?) {
15 | super.onCreate(savedInstanceState)
16 | registry.onCustomRestoreInstanceState(savedInstanceState)
17 | }
18 |
19 | override fun onSaveInstanceState(outState: Bundle) {
20 | super.onSaveInstanceState(outState)
21 | registry.onCustomSaveInstanceState(outState)
22 | }
23 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/ActivityResultInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 | import androidx.annotation.Nullable;
5 |
6 | public class ActivityResultInfo {
7 |
8 | @NonNull
9 | public final String sourceUuid;
10 |
11 | public ActivityResultInfo(@NonNull String sourceUuid) {
12 | this.sourceUuid = sourceUuid;
13 | }
14 |
15 | @NonNull
16 | public ActivityResultSource getCaller() {
17 | ActivityResultSource caller = getSafeCaller();
18 | if (caller == null) throw new IllegalStateException("must call after source onCreate");
19 | return caller;
20 | }
21 |
22 | @Nullable
23 | public ActivityResultSource getSafeCaller() {
24 | return ActivityResultManager.findSourceByUuid(sourceUuid);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/cn/hx/activityresultapi/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("cn.hx.activityresultapi", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/RequestMultiplePermissionsResultInfo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | import java.util.Map;
6 |
7 | public class RequestMultiplePermissionsResultInfo extends ActivityResultInfo {
8 |
9 | @NonNull
10 | public final String[] permissions;
11 | @NonNull
12 | public final Map grantState;
13 | @NonNull
14 | public final Map shouldRationale;
15 |
16 | public RequestMultiplePermissionsResultInfo(@NonNull String sourceUuid, @NonNull String[] permissions, @NonNull Map grantState, @NonNull Map shouldRationale) {
17 | super(sourceUuid);
18 | this.permissions = permissions;
19 | this.grantState = grantState;
20 | this.shouldRationale = shouldRationale;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/cn/hx/ara/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 | assertEquals("cn.hx.ara.test", appContext.getPackageName());
25 | }
26 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/debug/java/cn/hx/activityresultapi/TestActivity.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.os.Bundle
4 | import androidx.activity.result.ActivityResultRegistry
5 |
6 | class TestActivity : BaseActivity() {
7 |
8 | val registry = CustomActivityResultRegistry()
9 |
10 | override fun customRegistry(): ActivityResultRegistry? {
11 | return registry
12 | }
13 |
14 | override fun onCreate(savedInstanceState: Bundle?) {
15 | super.onCreate(savedInstanceState)
16 | registry.onCustomRestoreInstanceState(savedInstanceState)
17 | setContentView(R.layout.activity_test)
18 | savedInstanceState
19 | ?: supportFragmentManager.beginTransaction().add(R.id.container, TestFragment()).commit()
20 | }
21 |
22 | override fun onSaveInstanceState(outState: Bundle) {
23 | super.onSaveInstanceState(outState)
24 | registry.onCustomSaveInstanceState(outState)
25 | }
26 | }
--------------------------------------------------------------------------------
/library/gradle.properties:
--------------------------------------------------------------------------------
1 | #project
2 | GROUP=com.github.qq549631030
3 | VERSION_NAME=0.0.7
4 |
5 | POM_ARTIFACT_ID=activity-result-api
6 | POM_NAME=ActivityResultApi
7 | POM_PACKAGING=aar
8 |
9 | POM_DESCRIPTION=Activity Result Api
10 | POM_INCEPTION_YEAR=2022
11 |
12 | POM_URL=https://github.com/qq549631030/ActivityResultApi/
13 | POM_SCM_URL=https://github.com/qq549631030/ActivityResultApi/
14 | POM_SCM_CONNECTION=scm:git:git://github.com/qq549631030/ActivityResultApi.git
15 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/qq549631030/ActivityResultApi.git
16 |
17 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
18 | POM_LICENCE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt
19 | POM_LICENCE_DIST=repo
20 |
21 | POM_DEVELOPER_ID=qq549631030
22 | POM_DEVELOPER_NAME=huangx
23 | POM_DEVELOPER_URL=https://github.com/qq549631030/
24 |
25 | #signing.keyId=[you keyId last 8bit]
26 | #signing.password=[you key password]
27 | #signing.secretKeyRingFile=[you gpg key file location]
28 | #
29 | #mavenCentralUsername=[you sonatype username]
30 | #mavenCentralPassword=[you sonatype password]
31 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/CustomCaptureVideo.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.provider.MediaStore;
7 |
8 | import androidx.activity.result.contract.ActivityResultContract;
9 | import androidx.annotation.NonNull;
10 | import androidx.annotation.Nullable;
11 |
12 | public class CustomCaptureVideo extends ActivityResultContract {
13 |
14 | @NonNull
15 | @Override
16 | public Intent createIntent(@NonNull Context context, VideoConfig input) {
17 | Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE)
18 | .putExtra(MediaStore.EXTRA_OUTPUT, input.outputUri);
19 | intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, input.quality);
20 | if (input.durationLimit != 0) {
21 | intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, input.durationLimit);
22 | }
23 | if (input.sizeLimit != 0) {
24 | intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, input.sizeLimit);
25 | }
26 | return intent;
27 | }
28 |
29 | @Override
30 | public Boolean parseResult(int resultCode, @Nullable Intent intent) {
31 | return resultCode == Activity.RESULT_OK;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'com.vanniktech.maven.publish'
4 | }
5 |
6 | android {
7 | compileSdk 33
8 |
9 | defaultConfig {
10 | minSdk 14
11 | targetSdk 33
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles "consumer-rules.pro"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | sourceCompatibility JavaVersion.VERSION_1_8
25 | targetCompatibility JavaVersion.VERSION_1_8
26 | }
27 | }
28 | tasks.withType(Javadoc) {
29 | failOnError false
30 | options.addStringOption('Xdoclint:none', '-quiet')
31 | options.addStringOption('encoding', 'UTF-8')
32 | options.addStringOption('charSet', 'UTF-8')
33 | }
34 |
35 | dependencies {
36 |
37 | implementation 'androidx.activity:activity:1.2.0'
38 | implementation 'androidx.fragment:fragment:1.3.0'
39 | testImplementation 'junit:junit:4.13.2'
40 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
41 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
42 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
20 |
21 |
26 |
27 |
32 |
33 |
38 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=obsolete
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 |
25 | org.gradle.caching=true
26 | android.injected.testOnly=false
--------------------------------------------------------------------------------
/app/src/main/java/cn/hx/activityresultapi/CustomActivityResultRegistry.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import androidx.activity.result.ActivityResultRegistry
6 | import androidx.activity.result.contract.ActivityResultContract
7 | import androidx.core.app.ActivityOptionsCompat
8 |
9 | class CustomActivityResultRegistry : ActivityResultRegistry() {
10 | private var lastRequestCode = -1
11 |
12 | override fun onLaunch(requestCode: Int, contract: ActivityResultContract, input: I, options: ActivityOptionsCompat?) {
13 | lastRequestCode = requestCode
14 | }
15 |
16 | fun dispatchForLastRequest(resultCode: Int, data: Intent? = null) {
17 | if (lastRequestCode != -1) {
18 | dispatchResult(lastRequestCode, resultCode, data)
19 | lastRequestCode = -1
20 | }
21 | }
22 |
23 | fun onCustomSaveInstanceState(outState: Bundle) {
24 | onSaveInstanceState(outState)
25 | if (lastRequestCode != -1) {
26 | outState.putInt(LAST_REQUEST_CODE, lastRequestCode)
27 | }
28 | }
29 |
30 | fun onCustomRestoreInstanceState(savedInstanceState: Bundle?) {
31 | onRestoreInstanceState(savedInstanceState)
32 | savedInstanceState?.run {
33 | lastRequestCode = getInt(LAST_REQUEST_CODE, -1)
34 | }
35 | }
36 |
37 | companion object {
38 | const val LAST_REQUEST_CODE = "cn.hx.base.lastRequestCode"
39 | }
40 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/ActivityResultSource.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 |
6 | import androidx.activity.result.ActivityResultRegistry;
7 | import androidx.annotation.NonNull;
8 | import androidx.annotation.Nullable;
9 | import androidx.annotation.RestrictTo;
10 | import androidx.core.app.ActivityOptionsCompat;
11 |
12 | public interface ActivityResultSource {
13 |
14 | String ACTIVITY_RESULT_SOURCE_UUID = "cn.hx.ara.source.uuid";
15 |
16 | @RestrictTo(RestrictTo.Scope.LIBRARY)
17 | @NonNull
18 | ActivityResultSourceDelegate getActivityResultSourceDelegate();
19 |
20 | @Nullable
21 | ActivityResultRegistry customRegistry();
22 |
23 | @NonNull
24 | String getSourceUuid();
25 |
26 | void startActivityForResult(@NonNull Intent intent, @NonNull final ActivityResultCallback callback);
27 |
28 | void startActivityForResult(@NonNull Intent intent, @Nullable ActivityOptionsCompat optionsCompat, @NonNull final ActivityResultCallback callback);
29 |
30 | void takePicture(@NonNull Uri outputUri, @NonNull final TakePictureCallback callback);
31 |
32 | void takeVideo(@NonNull Uri outputUri, @NonNull final TakeVideoCallback callback);
33 |
34 | void takeVideo(@NonNull VideoConfig config, @NonNull final TakeVideoCallback callback);
35 |
36 | void requestPermission(@NonNull String permission, @NonNull final RequestPermissionCallback callback);
37 |
38 | void requestMultiplePermissions(@NonNull String[] permissions, @NonNull final RequestMultiplePermissionsCallback callback);
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
19 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
35 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | compileSdk 32
8 |
9 | defaultConfig {
10 | applicationId "cn.hx.activityresultapi"
11 | minSdk 14
12 | targetSdk 32
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 | buildFeatures {
19 | viewBinding true
20 | }
21 | buildTypes {
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 | compileOptions {
28 | sourceCompatibility JavaVersion.VERSION_1_8
29 | targetCompatibility JavaVersion.VERSION_1_8
30 | }
31 | kotlinOptions {
32 | jvmTarget = '1.8'
33 | }
34 | testOptions {
35 | unitTests {
36 | includeAndroidResources = true
37 | returnDefaultValues = true
38 | all {
39 | systemProperty 'robolectric.dependency.repo.url', 'https://maven.aliyun.com/repository/public/'
40 | systemProperty 'robolectric.dependency.repo.id', 'aliyun'
41 | }
42 | }
43 | }
44 | }
45 |
46 | dependencies {
47 |
48 | implementation 'androidx.appcompat:appcompat:1.2.0'
49 | implementation 'com.google.android.material:material:1.2.0'
50 | implementation project(path: ':library')
51 | testImplementation 'junit:junit:4.13.2'
52 | testImplementation "org.robolectric:robolectric:4.8.1"
53 | testImplementation 'androidx.test.ext:junit:1.1.3'
54 | testImplementation 'androidx.test.espresso:espresso-core:3.4.0'
55 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
56 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
57 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android Activity Result API 封装
2 | androidx.activity 1.2.0 开始新加了Activity Result API,原本的startActivityForResult被标记为过时的。
3 | 官方做法是要在onStart之前registerForActivityResult,这就导致必须提前知道当前页面会发起哪些页面请求提前注册,但是往往我们不一定确定当前页面会发生什么,比如跳转到登录页面。
4 | 本库做了下封装,可以在任意时机调用,并且在回调参数里增加了调用者(caller)和启动Intent,这在Activity recreate的情况下非常有用!
5 |
6 | 要验证效果,可在“开发者选项”中把“不保留活动”打开
7 |
8 | ### gradle依赖
9 |
10 | ```groovy
11 | dependencies {
12 | implementation 'com.github.qq549631030:activity-result-api:x.x.x'
13 | }
14 | ```
15 |
16 | ### 初始化配置
17 |
18 | #### 1、初始化
19 |
20 | 在Application的onCreate方法调用ActivityResultManager.init(this)初始化
21 |
22 | ```kotlin
23 | class BaseApplication : Application() {
24 |
25 | override fun onCreate() {
26 | super.onCreate()
27 | ActivityResultManager.init(this)
28 | }
29 | }
30 | ```
31 |
32 | #### 2、ActivityResultSource配置
33 |
34 | 通过代理方式:
35 |
36 | ActivityResultSource by ActivityResultSourceImpl()完成任意Activity和Fragment配置
37 |
38 | ```kotlin
39 | open class BaseActivity : AppCompatActivity(), ActivityResultSource by ActivityResultSourceImpl() {
40 | }
41 | open class BaseFragment : Fragment(), ActivityResultSource by ActivityResultSourceImpl() {
42 | }
43 | ```
44 |
45 | #### 3、使用
46 |
47 | ```kotlin
48 | startActivityForResult(Intent(this, SecondActivity::class.java)) {
49 | //回调参数ActivityResultInfo各属性说明:
50 | //resultCode:调用结果
51 | //data:额外返回数据
52 | //sourceUuid:调用者uuid
53 | //startIntent:启动本次调用的Intent
54 | //getCaller()方法: 返回非空调用者,为空抛异常(通常不会出现,除非在调用者onCreate之前调用)
55 | //getSafeCaller()方法: 返回可空调用者,
56 |
57 | //这里只能通过getCaller()访问外部类的方法、属性
58 | //不可直接访问外部类方法、属性,因为Activity recreate后的情况下原调用者已经不存在了
59 | //getCaller()是本库的精华所在,在Activity recreate后getCaller()是重建后的Activity或Fragment
60 | (it.caller as YourActivityResultSourceActivity).someMethod(it.resultCode, it.data, it.startIntent)
61 | (it.caller as YourActivityResultSourceFragment).someMethod(it.resultCode, it.data, it.startIntent)
62 | }
63 | ```
64 |
65 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/ActivityResultSourceImpl.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 |
6 | import androidx.activity.result.ActivityResultRegistry;
7 | import androidx.annotation.NonNull;
8 | import androidx.annotation.Nullable;
9 | import androidx.core.app.ActivityOptionsCompat;
10 |
11 | public class ActivityResultSourceImpl implements ActivityResultSource {
12 |
13 | private final ActivityResultSourceDelegate delegate = new ActivityResultSourceDelegate();
14 |
15 | @NonNull
16 | @Override
17 | public ActivityResultSourceDelegate getActivityResultSourceDelegate() {
18 | return delegate;
19 | }
20 |
21 | @Nullable
22 | @Override
23 | public ActivityResultRegistry customRegistry() {
24 | return null;
25 | }
26 |
27 | @NonNull
28 | @Override
29 | public String getSourceUuid() {
30 | return delegate.getUuid();
31 | }
32 |
33 | @Override
34 | public void startActivityForResult(@NonNull Intent intent, @NonNull ActivityResultCallback callback) {
35 | startActivityForResult(intent, null, callback);
36 | }
37 |
38 | @Override
39 | public void startActivityForResult(@NonNull Intent intent, @Nullable ActivityOptionsCompat optionsCompat, @NonNull ActivityResultCallback callback) {
40 | delegate.startActivityForResult(intent, optionsCompat, callback);
41 | }
42 |
43 | @Override
44 | public void takePicture(@NonNull Uri outputUri, @NonNull TakePictureCallback callback) {
45 | delegate.takePicture(outputUri, callback);
46 | }
47 |
48 | @Override
49 | public void takeVideo(@NonNull Uri outputUri, @NonNull TakeVideoCallback callback) {
50 | delegate.takeVideo(new VideoConfig(outputUri), callback);
51 | }
52 |
53 | @Override
54 | public void takeVideo(@NonNull VideoConfig config, @NonNull TakeVideoCallback callback) {
55 | delegate.takeVideo(config, callback);
56 | }
57 |
58 | @Override
59 | public void requestPermission(@NonNull String permission, @NonNull RequestPermissionCallback callback) {
60 | delegate.requestPermission(permission, callback);
61 | }
62 |
63 | @Override
64 | public void requestMultiplePermissions(@NonNull String[] permissions, @NonNull RequestMultiplePermissionsCallback callback) {
65 | delegate.requestMultiplePermissions(permissions, callback);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/hx/activityresultapi/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.Manifest
4 | import android.content.Intent
5 | import android.content.pm.PackageManager
6 | import android.net.Uri
7 | import android.os.Build
8 | import android.os.Bundle
9 | import android.util.Log
10 | import androidx.core.app.ActivityCompat
11 | import androidx.core.content.FileProvider
12 | import cn.hx.activityresultapi.databinding.ActivityMainBinding
13 | import cn.hx.ara.VideoConfig
14 | import java.io.File
15 |
16 | class MainActivity : BaseActivity() {
17 |
18 | private lateinit var binding: ActivityMainBinding
19 |
20 | override fun onCreate(savedInstanceState: Bundle?) {
21 | super.onCreate(savedInstanceState)
22 | binding = ActivityMainBinding.inflate(layoutInflater)
23 | setContentView(binding.root)
24 | binding.btnStartActivity.setOnClickListener {
25 | startActivityForResult(Intent(this, SecondActivity::class.java)) {
26 | (it.caller as? MainActivity)?.receiveResult(it.resultCode, it.data)
27 | }
28 | }
29 | binding.btnTakePicture.setOnClickListener {
30 | val file = File(externalCacheDir, "${System.currentTimeMillis()}.jpg")
31 | val outputUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
32 | FileProvider.getUriForFile(this, "$packageName.provider", file)
33 | } else {
34 | Uri.fromFile(file)
35 | }
36 | takePicture(outputUri) {
37 | (it.caller as? MainActivity)?.takePictureResult(it.success, it.outputUri)
38 | }
39 | }
40 | binding.btnTakeVideo.setOnClickListener {
41 | val file = File(externalCacheDir, "${System.currentTimeMillis()}.mp4")
42 | val outputUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
43 | FileProvider.getUriForFile(this, "$packageName.provider", file)
44 | } else {
45 | Uri.fromFile(file)
46 | }
47 | takeVideo(outputUri) {
48 | (it.caller as? MainActivity)?.takeVideoResult(it.success, it.outputUri)
49 | }
50 | }
51 | binding.btnTakeVideoConfig.setOnClickListener {
52 | val file = File(externalCacheDir, "${System.currentTimeMillis()}.mp4")
53 | val outputUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
54 | FileProvider.getUriForFile(this, "$packageName.provider", file)
55 | } else {
56 | Uri.fromFile(file)
57 | }
58 | takeVideo(VideoConfig(outputUri, 1, 10, 10 * 1024 * 1024L)) {
59 | (it.caller as? MainActivity)?.takeVideoResult(it.success, it.outputUri)
60 | }
61 | }
62 | binding.btnRequestPerm.setOnClickListener {
63 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
64 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
65 | Log.d(TAG, "no permission ${Manifest.permission.READ_EXTERNAL_STORAGE} do request....")
66 | requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE) {
67 | Log.d(TAG, "requestPermission ${it.permission}: result = ${it.grantState}, shouldShowRequestPermissionRationale = ${it.shouldRationale}")
68 | }
69 | } else {
70 | Log.d(TAG, "have permission ${Manifest.permission.READ_EXTERNAL_STORAGE}")
71 | }
72 | }
73 | }
74 | }
75 |
76 | private fun receiveResult(resultCode: Int, data: Intent?) {
77 | Log.d(TAG, "receiveResult() called with: resultCode = $resultCode, data = $data")
78 | }
79 |
80 | private fun takePictureResult(success: Boolean, outputUri: Uri) {
81 | Log.d(TAG, "takePictureResult() called with: success = $success, outputUri = $outputUri")
82 | }
83 |
84 | private fun takeVideoResult(success: Boolean, outputUri: Uri) {
85 | Log.d(TAG, "takeVideoResult() called with: success = $success, outputUri = $outputUri")
86 | }
87 | }
--------------------------------------------------------------------------------
/app/src/test/java/cn/hx/activityresultapi/BaseFragmentTest.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.net.Uri
7 | import androidx.test.core.app.ApplicationProvider
8 | import androidx.test.ext.junit.rules.ActivityScenarioRule
9 | import androidx.test.ext.junit.runners.AndroidJUnit4
10 | import org.junit.Rule
11 | import org.junit.Test
12 | import org.junit.runner.RunWith
13 | import java.io.File
14 |
15 | @RunWith(AndroidJUnit4::class)
16 | class BaseFragmentTest {
17 |
18 | @get:Rule
19 | val activityRule = ActivityScenarioRule(TestActivity::class.java)
20 |
21 | @Test
22 | fun startActivityForResult() {
23 | var resultCode: Int = -2
24 | activityRule.scenario.onActivity {
25 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
26 | fragment.startActivityForResult(Intent(it, SecondActivity::class.java)) {
27 | resultCode = it.resultCode
28 | }
29 | assert(resultCode == -2)
30 | fragment.registry.dispatchForLastRequest(Activity.RESULT_OK)
31 | assert(resultCode == Activity.RESULT_OK)
32 | }
33 | }
34 |
35 | @Test
36 | fun startActivityForResult_recreate() {
37 | var fragmentHash = 0
38 | var resultCode: Int = -2
39 | activityRule.scenario.onActivity {
40 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
41 | fragmentHash = fragment.hashCode()
42 | fragment.startActivityForResult(Intent(it, SecondActivity::class.java)) {
43 | fragmentHash = it.caller.hashCode()
44 | resultCode = it.resultCode
45 | }
46 | }
47 | activityRule.scenario.recreate()
48 | activityRule.scenario.onActivity {
49 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
50 | assert(fragment.hashCode() != fragmentHash)
51 | assert(resultCode == -2)
52 | fragment.registry.dispatchForLastRequest(Activity.RESULT_OK)
53 | assert(fragment.hashCode() == fragmentHash)
54 | assert(resultCode == Activity.RESULT_OK)
55 | }
56 | }
57 |
58 | @Test
59 | fun takePicture() {
60 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
61 | var result: Boolean? = null
62 | activityRule.scenario.onActivity {
63 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
64 | fragment.takePicture(outputUri) {
65 | result = it.success
66 | }
67 | assert(result == null)
68 | fragment.registry.dispatchForLastRequest(Activity.RESULT_OK)
69 | assert(result == true)
70 | }
71 | }
72 |
73 | @Test
74 | fun takePicture_recreate() {
75 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
76 | var fragmentHash = 0
77 | var result: Boolean? = null
78 | activityRule.scenario.onActivity {
79 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
80 | fragmentHash = fragment.hashCode()
81 | fragment.takePicture(outputUri) {
82 | fragmentHash = it.caller.hashCode()
83 | result = it.success
84 | }
85 | }
86 | activityRule.scenario.recreate()
87 | activityRule.scenario.onActivity {
88 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
89 | assert(fragment.hashCode() != fragmentHash)
90 | assert(result == null)
91 | fragment.registry.dispatchForLastRequest(Activity.RESULT_OK)
92 | assert(fragment.hashCode() == fragmentHash)
93 | assert(result == true)
94 | }
95 | }
96 |
97 | @Test
98 | fun takeVideo() {
99 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
100 | var result: Boolean? = null
101 | activityRule.scenario.onActivity {
102 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
103 | fragment.takeVideo(outputUri) {
104 | result = it.success
105 | }
106 | assert(result == null)
107 | fragment.registry.dispatchForLastRequest(Activity.RESULT_OK, null)
108 | assert(result == true)
109 | }
110 | }
111 |
112 | @Test
113 | fun takeVideo_recreate() {
114 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
115 | var fragmentHash = 0
116 | var result: Boolean? = null
117 | activityRule.scenario.onActivity {
118 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
119 | fragmentHash = fragment.hashCode()
120 | fragment.takeVideo(outputUri) {
121 | fragmentHash = it.caller.hashCode()
122 | result = it.success
123 | }
124 | }
125 | activityRule.scenario.recreate()
126 | activityRule.scenario.onActivity {
127 | val fragment = it.supportFragmentManager.findFragmentById(R.id.container) as TestFragment
128 | assert(fragment.hashCode() != fragmentHash)
129 | assert(result == null)
130 | fragment.registry.dispatchForLastRequest(Activity.RESULT_CANCELED, null)
131 | assert(fragment.hashCode() == fragmentHash)
132 | assert(result == false)
133 | }
134 | }
135 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/ActivityResultManager.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.app.Activity;
4 | import android.app.Application;
5 | import android.content.Context;
6 | import android.os.Bundle;
7 |
8 | import androidx.activity.result.ActivityResultCaller;
9 | import androidx.annotation.NonNull;
10 | import androidx.annotation.Nullable;
11 | import androidx.fragment.app.Fragment;
12 | import androidx.fragment.app.FragmentActivity;
13 | import androidx.fragment.app.FragmentManager;
14 |
15 | import java.util.HashMap;
16 | import java.util.Map;
17 | import java.util.concurrent.LinkedBlockingDeque;
18 |
19 | public class ActivityResultManager {
20 |
21 | static final Map activityResultSourceMap = new HashMap<>();
22 | static final Map> activityResultCallbackMap = new HashMap<>();
23 | static final Map> takePictureCallbackMap = new HashMap<>();
24 | static final Map> takeVideoCallbackMap = new HashMap<>();
25 | static final Map> requestPermissionCallbackMap = new HashMap<>();
26 | static final Map> requestMultiplePermissionsCallbackMap = new HashMap<>();
27 |
28 | public static void init(Context context) {
29 | ((Application) context.getApplicationContext()).registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
30 | @Override
31 | public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
32 | if (activity instanceof ActivityResultSource && activity instanceof ActivityResultCaller) {
33 | ActivityResultSourceDelegate activityResultSourceDelegate = ((ActivityResultSource) activity).getActivityResultSourceDelegate();
34 | activityResultSourceDelegate.init((ActivityResultSource) activity, bundle);
35 | activityResultSourceMap.put(((ActivityResultSource) activity).getSourceUuid(), (ActivityResultSource) activity);
36 | }
37 | if (activity instanceof FragmentActivity) {
38 | ((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {
39 | @Override
40 | public void onFragmentCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {
41 | if (f instanceof ActivityResultSource) {
42 | ActivityResultSourceDelegate activityResultSourceDelegate = ((ActivityResultSource) f).getActivityResultSourceDelegate();
43 | activityResultSourceDelegate.init((ActivityResultSource) f, savedInstanceState);
44 | activityResultSourceMap.put(((ActivityResultSource) f).getSourceUuid(), (ActivityResultSource) f);
45 | }
46 | }
47 |
48 | @Override
49 | public void onFragmentSaveInstanceState(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull Bundle outState) {
50 | if (f instanceof ActivityResultSource) {
51 | outState.putString(ActivityResultSource.ACTIVITY_RESULT_SOURCE_UUID, ((ActivityResultSource) f).getSourceUuid());
52 | }
53 | }
54 |
55 | @Override
56 | public void onFragmentDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f) {
57 | if (f instanceof ActivityResultSource) {
58 | activityResultSourceMap.remove(((ActivityResultSource) f).getSourceUuid());
59 | if (f.isRemoving()) {
60 | activityResultCallbackMap.remove(((ActivityResultSource) f).getSourceUuid());
61 | takePictureCallbackMap.remove(((ActivityResultSource) f).getSourceUuid());
62 | takeVideoCallbackMap.remove(((ActivityResultSource) f).getSourceUuid());
63 | requestPermissionCallbackMap.remove(((ActivityResultSource) f).getSourceUuid());
64 | requestMultiplePermissionsCallbackMap.remove(((ActivityResultSource) f).getSourceUuid());
65 | }
66 | }
67 | }
68 | }, true);
69 | }
70 | }
71 |
72 | @Override
73 | public void onActivityStarted(@NonNull Activity activity) {
74 |
75 | }
76 |
77 | @Override
78 | public void onActivityResumed(@NonNull Activity activity) {
79 |
80 | }
81 |
82 | @Override
83 | public void onActivityPaused(@NonNull Activity activity) {
84 |
85 | }
86 |
87 | @Override
88 | public void onActivityStopped(@NonNull Activity activity) {
89 |
90 | }
91 |
92 | @Override
93 | public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {
94 | if (activity instanceof ActivityResultSource) {
95 | bundle.putString(ActivityResultSource.ACTIVITY_RESULT_SOURCE_UUID, ((ActivityResultSource) activity).getSourceUuid());
96 | }
97 | }
98 |
99 | @Override
100 | public void onActivityDestroyed(@NonNull Activity activity) {
101 | if (activity instanceof ActivityResultSource) {
102 | activityResultSourceMap.remove(((ActivityResultSource) activity).getSourceUuid());
103 | if (activity.isFinishing()) {
104 | activityResultCallbackMap.remove(((ActivityResultSource) activity).getSourceUuid());
105 | takePictureCallbackMap.remove(((ActivityResultSource) activity).getSourceUuid());
106 | takeVideoCallbackMap.remove(((ActivityResultSource) activity).getSourceUuid());
107 | requestPermissionCallbackMap.remove(((ActivityResultSource) activity).getSourceUuid());
108 | requestMultiplePermissionsCallbackMap.remove(((ActivityResultSource) activity).getSourceUuid());
109 | }
110 | }
111 | }
112 | });
113 | }
114 |
115 | @Nullable
116 | public static ActivityResultSource findSourceByUuid(@NonNull String uuid) {
117 | return activityResultSourceMap.get(uuid);
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/app/src/test/java/cn/hx/activityresultapi/BaseActivityTest.kt:
--------------------------------------------------------------------------------
1 | package cn.hx.activityresultapi
2 |
3 | import android.Manifest
4 | import android.app.Activity
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.content.pm.PackageManager
8 | import android.net.Uri
9 | import androidx.activity.result.contract.ActivityResultContracts
10 | import androidx.test.core.app.ApplicationProvider
11 | import androidx.test.ext.junit.rules.ActivityScenarioRule
12 | import androidx.test.ext.junit.runners.AndroidJUnit4
13 | import org.junit.Rule
14 | import org.junit.Test
15 | import org.junit.runner.RunWith
16 | import java.io.File
17 |
18 | @RunWith(AndroidJUnit4::class)
19 | class BaseActivityTest {
20 |
21 | @get:Rule
22 | val activityRule = ActivityScenarioRule(TestActivity::class.java)
23 |
24 | @Test
25 | fun startActivityForResult() {
26 | var resultCode: Int = -2
27 | activityRule.scenario.onActivity {
28 | it.startActivityForResult(Intent(it, SecondActivity::class.java)) {
29 | resultCode = it.resultCode
30 | }
31 | assert(resultCode == -2)
32 | it.registry.dispatchForLastRequest(Activity.RESULT_OK)
33 | assert(resultCode == Activity.RESULT_OK)
34 | }
35 | }
36 |
37 | @Test
38 | fun startActivityForResult_recreate() {
39 | var activityHash = 0
40 | var resultCode: Int = -2
41 | activityRule.scenario.onActivity {
42 | activityHash = it.hashCode()
43 | it.startActivityForResult(Intent(it, SecondActivity::class.java)) {
44 | activityHash = it.caller.hashCode()
45 | resultCode = it.resultCode
46 | }
47 | }
48 | activityRule.scenario.recreate()
49 | activityRule.scenario.onActivity {
50 | assert(it.hashCode() != activityHash)
51 | assert(resultCode == -2)
52 | it.registry.dispatchForLastRequest(Activity.RESULT_OK)
53 | assert(it.hashCode() == activityHash)
54 | assert(resultCode == Activity.RESULT_OK)
55 | }
56 | }
57 |
58 | @Test
59 | fun takePicture() {
60 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
61 | var result: Boolean? = null
62 | activityRule.scenario.onActivity {
63 | it.takePicture(outputUri) {
64 | result = it.success
65 | }
66 | assert(result == null)
67 | it.registry.dispatchForLastRequest(Activity.RESULT_OK)
68 | assert(result == true)
69 | }
70 | }
71 |
72 | @Test
73 | fun takePicture_recreate() {
74 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
75 | var activityHash = 0
76 | var result: Boolean? = null
77 | activityRule.scenario.onActivity {
78 | activityHash = it.hashCode()
79 | it.takePicture(outputUri) {
80 | activityHash = it.caller.hashCode()
81 | result = it.success
82 | }
83 | }
84 | activityRule.scenario.recreate()
85 | activityRule.scenario.onActivity {
86 | assert(it.hashCode() != activityHash)
87 | assert(result == null)
88 | it.registry.dispatchForLastRequest(Activity.RESULT_CANCELED)
89 | assert(it.hashCode() == activityHash)
90 | assert(result == false)
91 | }
92 | }
93 |
94 |
95 | @Test
96 | fun takeVideo() {
97 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
98 | var result: Boolean? = null
99 | activityRule.scenario.onActivity {
100 | it.takeVideo(outputUri) {
101 | result = it.success
102 | }
103 | assert(result == null)
104 | it.registry.dispatchForLastRequest(Activity.RESULT_OK, null)
105 | assert(result != null)
106 | }
107 | }
108 |
109 | @Test
110 | fun takeVideo_recreate() {
111 | val outputUri = Uri.parse(File(ApplicationProvider.getApplicationContext().cacheDir, "test.jpg").absolutePath)
112 | var activityHash = 0
113 | var result: Boolean? = null
114 | activityRule.scenario.onActivity {
115 | activityHash = it.hashCode()
116 | it.takeVideo(outputUri) {
117 | activityHash = it.caller.hashCode()
118 | result = it.success
119 | }
120 | }
121 | activityRule.scenario.recreate()
122 | activityRule.scenario.onActivity {
123 | assert(it.hashCode() != activityHash)
124 | assert(result == null)
125 | it.registry.dispatchForLastRequest(Activity.RESULT_CANCELED, null)
126 | assert(it.hashCode() == activityHash)
127 | assert(result == false)
128 | }
129 | }
130 |
131 | @Test
132 | fun requestPermission() {
133 | var grantState: Boolean? = null
134 |
135 | activityRule.scenario.onActivity {
136 | it.requestPermission(Manifest.permission.CAMERA) { result ->
137 | grantState = result.grantState
138 | }
139 | assert(grantState == null)
140 | it.registry.dispatchForLastRequest(Activity.RESULT_OK, Intent().apply {
141 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, arrayOf(Manifest.permission.CAMERA))
142 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS, intArrayOf(PackageManager.PERMISSION_GRANTED))
143 | })
144 | assert(grantState == true)
145 | }
146 | }
147 |
148 | @Test
149 | fun requestPermission_recreate() {
150 | var grantState: Boolean? = null
151 | activityRule.scenario.onActivity {
152 | it.requestPermission(Manifest.permission.CAMERA) { result ->
153 | grantState = result.grantState
154 | }
155 | assert(grantState == null)
156 | }
157 | activityRule.scenario.recreate()
158 | activityRule.scenario.onActivity {
159 | assert(grantState == null)
160 | it.registry.dispatchForLastRequest(Activity.RESULT_OK, Intent().apply {
161 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, arrayOf(Manifest.permission.CAMERA))
162 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS, intArrayOf(PackageManager.PERMISSION_DENIED))
163 | })
164 | assert(grantState == false)
165 | }
166 | }
167 |
168 | @Test
169 | fun requestMultiplePermissions() {
170 | var grantState: Map? = null
171 | activityRule.scenario.onActivity {
172 | it.requestMultiplePermissions(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)) { result ->
173 | grantState = result.grantState
174 | }
175 | assert(grantState == null)
176 | it.registry.dispatchForLastRequest(Activity.RESULT_OK, Intent().apply {
177 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO))
178 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS, intArrayOf(PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_GRANTED))
179 | })
180 | assert(grantState != null)
181 | assert(grantState?.get(Manifest.permission.CAMERA) == true)
182 | assert(grantState?.get(Manifest.permission.RECORD_AUDIO) == true)
183 | }
184 | }
185 |
186 | @Test
187 | fun requestMultiplePermissions_recreate() {
188 | var grantState: Map? = null
189 | activityRule.scenario.onActivity {
190 | it.requestMultiplePermissions(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)) { result ->
191 | grantState = result.grantState
192 | }
193 | assert(grantState == null)
194 | }
195 | activityRule.scenario.recreate()
196 | activityRule.scenario.onActivity {
197 | it.registry.dispatchForLastRequest(Activity.RESULT_OK, Intent().apply {
198 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO))
199 | putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS, intArrayOf(PackageManager.PERMISSION_DENIED, PackageManager.PERMISSION_GRANTED))
200 | })
201 | assert(grantState != null)
202 | assert(grantState?.get(Manifest.permission.CAMERA) == false)
203 | assert(grantState?.get(Manifest.permission.RECORD_AUDIO) == true)
204 | }
205 | }
206 | }
--------------------------------------------------------------------------------
/library/src/main/java/cn/hx/ara/ActivityResultSourceDelegate.java:
--------------------------------------------------------------------------------
1 | package cn.hx.ara;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.net.Uri;
6 | import android.os.Bundle;
7 |
8 | import androidx.activity.result.ActivityResult;
9 | import androidx.activity.result.ActivityResultCaller;
10 | import androidx.activity.result.ActivityResultLauncher;
11 | import androidx.activity.result.ActivityResultRegistry;
12 | import androidx.activity.result.contract.ActivityResultContracts;
13 | import androidx.annotation.NonNull;
14 | import androidx.annotation.Nullable;
15 | import androidx.core.app.ActivityCompat;
16 | import androidx.core.app.ActivityOptionsCompat;
17 | import androidx.fragment.app.Fragment;
18 |
19 | import java.util.HashMap;
20 | import java.util.Map;
21 | import java.util.UUID;
22 | import java.util.concurrent.LinkedBlockingDeque;
23 |
24 | public class ActivityResultSourceDelegate {
25 |
26 | private String mUuid;
27 |
28 | private ActivityResultLauncher activityResultLauncher;
29 | private ActivityResultLauncher takePictureLauncher;
30 | private ActivityResultLauncher takeVideoLauncher;
31 | private ActivityResultLauncher requestPermissionLauncher;
32 | private ActivityResultLauncher requestMultiplePermissionsLauncher;
33 |
34 | @NonNull
35 | String getUuid() {
36 | if (mUuid == null) {
37 | mUuid = UUID.randomUUID().toString();
38 | }
39 | return mUuid;
40 | }
41 |
42 | void init(@NonNull ActivityResultSource activityResultSource, @Nullable Bundle savedInstanceState) {
43 | if (savedInstanceState != null) {
44 | mUuid = savedInstanceState.getString(ActivityResultSource.ACTIVITY_RESULT_SOURCE_UUID);
45 | }
46 | ActivityResultRegistry customRegistry = activityResultSource.customRegistry();
47 | if (customRegistry != null) {
48 | activityResultLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), customRegistry, result -> {
49 | dispatchStartActivityResult(activityResultSource, result);
50 | });
51 | takePictureLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.TakePicture(), customRegistry, result -> {
52 | dispatchTakePictureResult(activityResultSource, result);
53 | });
54 | takeVideoLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new CustomCaptureVideo(), customRegistry, result -> {
55 | dispatchTakeVideoResult(activityResultSource, result);
56 | });
57 | requestPermissionLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.RequestPermission(), customRegistry, result -> {
58 | dispatchRequestPermissionResult(activityResultSource, result);
59 | });
60 | requestMultiplePermissionsLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), customRegistry, result -> {
61 | dispatchRequestMultiplePermissionsResult(activityResultSource, result);
62 | });
63 | } else {
64 | activityResultLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
65 | dispatchStartActivityResult(activityResultSource, result);
66 | });
67 | takePictureLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
68 | dispatchTakePictureResult(activityResultSource, result);
69 | });
70 | takeVideoLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new CustomCaptureVideo(), result -> {
71 | dispatchTakeVideoResult(activityResultSource, result);
72 | });
73 | requestPermissionLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.RequestPermission(), result -> {
74 | dispatchRequestPermissionResult(activityResultSource, result);
75 | });
76 | requestMultiplePermissionsLauncher = ((ActivityResultCaller) activityResultSource).registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
77 | dispatchRequestMultiplePermissionsResult(activityResultSource, result);
78 | });
79 | }
80 | }
81 |
82 | @NonNull
83 | LinkedBlockingDeque getStartActivityInfo() {
84 | LinkedBlockingDeque resultCallbacks = ActivityResultManager.activityResultCallbackMap.get(getUuid());
85 | if (resultCallbacks == null) {
86 | resultCallbacks = new LinkedBlockingDeque<>();
87 | ActivityResultManager.activityResultCallbackMap.put(getUuid(), resultCallbacks);
88 | }
89 | return resultCallbacks;
90 | }
91 |
92 | @NonNull
93 | LinkedBlockingDeque getTakePictureInfo() {
94 | LinkedBlockingDeque resultCallbacks = ActivityResultManager.takePictureCallbackMap.get(getUuid());
95 | if (resultCallbacks == null) {
96 | resultCallbacks = new LinkedBlockingDeque<>();
97 | ActivityResultManager.takePictureCallbackMap.put(getUuid(), resultCallbacks);
98 | }
99 | return resultCallbacks;
100 | }
101 |
102 | @NonNull
103 | LinkedBlockingDeque getTakeVideoInfo() {
104 | LinkedBlockingDeque resultCallbacks = ActivityResultManager.takeVideoCallbackMap.get(getUuid());
105 | if (resultCallbacks == null) {
106 | resultCallbacks = new LinkedBlockingDeque<>();
107 | ActivityResultManager.takeVideoCallbackMap.put(getUuid(), resultCallbacks);
108 | }
109 | return resultCallbacks;
110 | }
111 |
112 | @NonNull
113 | LinkedBlockingDeque getRequestPermissionInfo() {
114 | LinkedBlockingDeque resultCallbacks = ActivityResultManager.requestPermissionCallbackMap.get(getUuid());
115 | if (resultCallbacks == null) {
116 | resultCallbacks = new LinkedBlockingDeque<>();
117 | ActivityResultManager.requestPermissionCallbackMap.put(getUuid(), resultCallbacks);
118 | }
119 | return resultCallbacks;
120 | }
121 |
122 | @NonNull
123 | LinkedBlockingDeque getRequestMultiplePermissionsInfo() {
124 | LinkedBlockingDeque resultCallbacks = ActivityResultManager.requestMultiplePermissionsCallbackMap.get(getUuid());
125 | if (resultCallbacks == null) {
126 | resultCallbacks = new LinkedBlockingDeque<>();
127 | ActivityResultManager.requestMultiplePermissionsCallbackMap.put(getUuid(), resultCallbacks);
128 | }
129 | return resultCallbacks;
130 | }
131 |
132 | void startActivityForResult(@NonNull Intent intent, @Nullable ActivityOptionsCompat optionsCompat, @NonNull ActivityResultCallback callback) {
133 | getStartActivityInfo().offerFirst(new StartActivityInfo(intent, optionsCompat, callback));
134 | activityResultLauncher.launch(intent, optionsCompat);
135 | }
136 |
137 | void takePicture(@NonNull Uri outputUri, @NonNull TakePictureCallback callback) {
138 | getTakePictureInfo().offerFirst(new TakePictureInfo(outputUri, callback));
139 | takePictureLauncher.launch(outputUri);
140 | }
141 |
142 | void takeVideo(@NonNull VideoConfig config, @NonNull TakeVideoCallback callback) {
143 | getTakeVideoInfo().offerFirst(new TakeVideoInfo(config, callback));
144 | takeVideoLauncher.launch(config);
145 | }
146 |
147 | void requestPermission(@NonNull String permission, @NonNull RequestPermissionCallback callback) {
148 | getRequestPermissionInfo().offerFirst(new RequestPermissionInfo(permission, callback));
149 | requestPermissionLauncher.launch(permission);
150 | }
151 |
152 | void requestMultiplePermissions(@NonNull String[] permissions, @NonNull RequestMultiplePermissionsCallback callback) {
153 | getRequestMultiplePermissionsInfo().offerFirst(new RequestMultiplePermissionsInfo(permissions, callback));
154 | requestMultiplePermissionsLauncher.launch(permissions);
155 | }
156 |
157 | void dispatchStartActivityResult(@NonNull ActivityResultSource activityResultSource, @NonNull ActivityResult result) {
158 | StartActivityInfo startActivityInfo = getStartActivityInfo().pollFirst();
159 | if (startActivityInfo != null) {
160 | startActivityInfo.callback.onActivityResult(new StartActivityResultInfo(activityResultSource.getSourceUuid(), result.getResultCode(), result.getData(), startActivityInfo.intent));
161 | }
162 | }
163 |
164 | void dispatchTakePictureResult(@NonNull ActivityResultSource activityResultSource, boolean result) {
165 | TakePictureInfo takePictureInfo = getTakePictureInfo().pollFirst();
166 | if (takePictureInfo != null) {
167 | takePictureInfo.callback.onTakePictureResult(new TakePictureResultInfo(activityResultSource.getSourceUuid(), result, takePictureInfo.outputUri));
168 | }
169 | }
170 |
171 | void dispatchTakeVideoResult(@NonNull ActivityResultSource activityResultSource, boolean result) {
172 | TakeVideoInfo takeVideoInfo = getTakeVideoInfo().pollFirst();
173 | if (takeVideoInfo != null) {
174 | takeVideoInfo.callback.onTakeVideoResult(new TakeVideoResultInfo(activityResultSource.getSourceUuid(), result, takeVideoInfo.config.outputUri));
175 | }
176 | }
177 |
178 | void dispatchRequestPermissionResult(@NonNull ActivityResultSource activityResultSource, Boolean result) {
179 | RequestPermissionInfo requestPermissionInfo = getRequestPermissionInfo().pollFirst();
180 | if (requestPermissionInfo != null) {
181 | boolean shouldRationale = false;
182 | if (!result) {
183 | shouldRationale = shouldShowRequestPermissionRationale(activityResultSource, requestPermissionInfo.permission);
184 | }
185 | requestPermissionInfo.callback.onRequestPermissionResult(new RequestPermissionResultInfo(activityResultSource.getSourceUuid(), requestPermissionInfo.permission, result, shouldRationale));
186 | }
187 | }
188 |
189 | void dispatchRequestMultiplePermissionsResult(@NonNull ActivityResultSource activityResultSource, Map result) {
190 | RequestMultiplePermissionsInfo requestMultiplePermissionsInfo = getRequestMultiplePermissionsInfo().pollFirst();
191 | if (requestMultiplePermissionsInfo != null) {
192 | Map shouldRationale = new HashMap<>();
193 | for (Map.Entry entry : result.entrySet()) {
194 | if (!entry.getValue()) {
195 | shouldRationale.put(entry.getKey(), shouldShowRequestPermissionRationale(activityResultSource, entry.getKey()));
196 | }
197 | }
198 | requestMultiplePermissionsInfo.callback.onRequestMultiplePermissionsResult(new RequestMultiplePermissionsResultInfo(activityResultSource.getSourceUuid(), requestMultiplePermissionsInfo.permissions, result, shouldRationale));
199 | }
200 | }
201 |
202 | private boolean shouldShowRequestPermissionRationale(@NonNull ActivityResultSource activityResultSource, @NonNull String permission) {
203 | boolean shouldRationale = false;
204 | Activity activity = null;
205 | if (activityResultSource instanceof Activity) {
206 | activity = (Activity) activityResultSource;
207 |
208 | } else if (activityResultSource instanceof Fragment) {
209 | activity = ((Fragment) activityResultSource).getActivity();
210 | }
211 | if (activity != null) {
212 | shouldRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
213 | }
214 | return shouldRationale;
215 | }
216 | }
217 |
--------------------------------------------------------------------------------