深入理解Activity Result API:ActivityResultContract的实现原理

简介: AndroidX从Activity:1.2.0-alpha02 和 Fragment:1.3.0-alpha02 起追加了Result API,使用ActivityResultContract替代st

在这里插入图片描述
AndroidX从Activity:1.2.0-alpha02Fragment:1.3.0-alpha02 起追加了Result API,使用ActivityResultContract替代startActivityForResult,更加高效且typesafe的处理跨Activity通信。目前Result API已升级到rc版,相对于alpha版API上有所变化,本文内容基于1.2.0-rc-01

参考:alpha版的Result API

如何使用

在AppCompatActivity或者Fragment中通过registerForActivityResult()创建ActivityResultLauncher,然后调用launch(...)替代startActivityForResult启动目标Activity。

//MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
      
        fab.setOnClickListener { view ->
            val intent = Intent(this, MainActivity::class.java)
            launcher.launch(intent)
        }
    }
  
    // Create ActivityResultLauncher
    private val launcher : ActivityResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            activityResult ->
                   // activityResult will return this as ActivityResult                                                
                    Log.d("MainActivity", activityResult.toString())
                //  D/MainActivity: ActivityResult{resultCode=RESULT_OK, data=Intent { (has extras) }}
            }
}
//SecondActivity.kt
class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setResult(Activity.RESULT_OK, Intent().putExtra("my-data", "data"))
        finish()
    }
}

源码分析

Result API能以近似回调的形式替代startActivityResult,核心是ActivityResultContract这个协议类。ActivityResultContracts中预置了多个ActivityResultContract的实现,StartActivityForResul便是其中之一。

StartActivityForResult

//ActivityResultContracts.java
public static final class StartActivityForResult
            extends ActivityResultContract<Intent, ActivityResult> {

        @NonNull
        @Override
        public Intent createIntent(@NonNull Context context, @NonNull Intent input) {
            return input;
        }

        @NonNull
        @Override
        public ActivityResult parseResult(
                int resultCode, @Nullable Intent intent) {
            return new ActivityResult(resultCode, intent);
        }
    }

ActivityResultContract接受两个泛型,分别表示ActivityResultLauncher的启动参数类型以及onActivityResult返回的结果类型。对于StartActivityForResult来说,通过Intent启动,等待目标Activity返回ActivityResult

自定义ActivityResultContract

当然,你可以自定义ActivityResultContract,接受任意类型的启动参数。然后在createIntent中构造Intent,例如:

//PostActivityContract.kt
class PostActivityContract : ActivityResultContract<Int, String?>() {
    override fun createIntent(context: Context, input: Int): Intent {
        return Intent(context, PostActivity::class.java).apply {
            putExtra("PostActivity.ID", input)
        }
    }

    override fun parseResult(resultCode: Int, intent: Intent?): String? {
        val data = intent?.getStringExtra(PostActivity.TITLE)
        return if (resultCode == Activity.RESULT_OK && data != null) data
        else null
    }
}
// MainActivity.kt
launcher.launch(100089) //launch with Int

private val launcher =
    registerForActivityResult(PostActivityContract()) { result ->
        // Result will return this as string?                                              
        if (result != null) toast("Result : $result")
        else toast("No Result")
    }

ActivityResultRegistry

registerForActivityResult内调用ActivityResultRegistryregister()方法

//ComponentActivity.java

      @NonNull
    @Override
    public final <I, O> ActivityResultLauncher<I> registerForActivityResult(
            @NonNull final ActivityResultContract<I, O> contract,
            @NonNull final ActivityResultRegistry registry,
            @NonNull final ActivityResultCallback<O> callback) {
        return registry.register(
                "activity_rq#" + mNextLocalRequestCode.getAndIncrement(), this, contract, callback);
    }

    @NonNull
    @Override
    public final <I, O> ActivityResultLauncher<I> registerForActivityResult(
            @NonNull ActivityResultContract<I, O> contract,
            @NonNull ActivityResultCallback<O> callback) {
        return registerForActivityResult(contract, mActivityResultRegistry, callback);
    }

    @NonNull
    @Override
    public final ActivityResultRegistry getActivityResultRegistry() {
        return mActivityResultRegistry;
    }

register()内部会将ActivityResultContract存入一个HashMap中。你也可以不使用mActivityResultRegistry,使用自定义的ActivityResultRegistry,例如

val launcher: ActivityResultLauncher<Intent> = activityResultRegistry
        .register(ActivityResultContracts.StartActivityForResult(),
                "activity_rq#0",
                this, //LifecyleOwner: ComponentActivity
        ) { activityResult: ActivityResult ->
            Log.d("MainActivity", activityResult.toString())
            //  D/MainActivity: ActivityResult{resultCode=RESULT_OK, data=Intent { (has extras) }}
        }

register接受一个LifecycleOwner(ComponentActivity自身),在合适的生命周期将回调存入/移除Map,保证回调响应的时机正确。

LifecycleEventObserver observer = new LifecycleEventObserver() {
            @Override
            public void onStateChanged(
                    @NonNull LifecycleOwner lifecycleOwner,
                    @NonNull Lifecycle.Event event) {
                if (Lifecycle.Event.ON_START.equals(event)) {
                    mKeyToCallback.put(key, new CallbackAndContract<>(callback, contract));
                    ...
                } else if (Lifecycle.Event.ON_STOP.equals(event)) {
                    mKeyToCallback.remove(key);
                } else if (Lifecycle.Event.ON_DESTROY.equals(event)) {
                    unregister(key);
                }
            }
        };

ComponentActivity相关实现

ComponentActivity比较简单,持有ActivityResultRegistry,并提供registerForActivityResult方法。ActivityResultRegistry中通过HashMap存储回调,HashMap的key是自增的。

 "activity_rq#" + mNextLocalRequestCode.getAndIncrement()

在这里插入图片描述

还需要requestCode吗

以往onActivityResult需要通过requestCode来识别是哪个startActivityForResult的返回,现在可以通过AutoIncrement来管理。而且当进程被杀时onSaveInstanceState会自动保存requestCode和ActivityResultRegistry的key的pair对,当onActivityResult返回requestCode时,可以通过对应关系找到key,然后找到ActivityResultCallback.

//ActivityResultRegistry.java
private int registerKey(String key) {
        Integer existing = mKeyToRc.get(key);
        if (existing != null) {
            return existing;
        }
        int rc = mNextRc.getAndIncrement();
        bindRcKey(rc, key);
        return rc;
    }

Fragment相关实现

Fragment.registerForActivityResult()内部,在onAttach的时候,会调用getActivity().getActivityResultRegistry()进行register

//Fragment.java
    public final <I, O> ActivityResultLauncher<I> registerForActivityResult(
            @NonNull final ActivityResultContract<I, O> contract,
            @NonNull final ActivityResultCallback<O> callback) {
        return prepareCallInternal(contract, new Function<Void, ActivityResultRegistry>() {
            @Override
            public ActivityResultRegistry apply(Void input) {
                if (mHost instanceof ActivityResultRegistryOwner) {
                    return ((ActivityResultRegistryOwner) mHost).getActivityResultRegistry();
                }
                return requireActivity().getActivityResultRegistry();
            }
        }, callback);
    }


    @NonNull
    private <I, O> ActivityResultLauncher<I> prepareCallInternal(
            @NonNull final ActivityResultContract<I, O> contract,
            @NonNull final Function<Void, ActivityResultRegistry> registryProvider,
            @NonNull final ActivityResultCallback<O> callback) {
...
        registerOnPreAttachListener(new OnPreAttachedListener() {
            @Override
            void onPreAttached() {
                final String key = generateActivityResultKey();
                ActivityResultRegistry registry = registryProvider.apply(null);
                ref.set(registry.register(key, Fragment.this, contract, callback));
            }
        });
        
        return new ActivityResultLauncher<I>() {
            @Override
            public void launch(I input) {
...
            }
        };
    }

    private void registerOnPreAttachListener(@NonNull final OnPreAttachedListener callback) {
        //If we are already attached, we can register immediately
        if (mState >= ATTACHED) {
            callback.onPreAttached();
        } else {
            // else we need to wait until we are attached
            mOnPreAttachedListeners.add(callback);
        }
    }

register虽然将framgent实例注入到上级持有的HashMap,但是此时使用的LifecycleOwner是Fragment自身,前文分析可知,在其ON_DESTROY的时候会进行对应的后处理,因此不必担心造成内存泄漏。

更多预置ActivityResultContract

除了StartActivityFroResult以外,还有很多预知的ActivityResultContract:
在这里插入图片描述

例如,通过GetContent打开文件管理器选择图片并返回URI:

class MainActivity : AppCompatActivity() {

    private val launcher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        Log.d("MainActivity", "uri: $uri")
    }

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

        button_get_content.setOnClickListener {
            launcher.launch("image/*")
        }
    }
}

通过RequestPermissionRequestMultiplePermission 进行权限申请也将变得更加简单:

request_permission.setOnClickListener {
    requestPermission.launch(permission.BLUETOOTH)
}

request_multiple_permission.setOnClickListener {
    requestMultiplePermissions.launch(
        arrayOf(
            permission.BLUETOOTH,
            permission.NFC,
            permission.ACCESS_FINE_LOCATION
        )
    )
}

// Request permission contract
private val requestPermission =
    registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        // Do something if permission granted
        if (isGranted) toast("Permission is granted")
        else toast("Permission is denied")
    }

// Request multiple permissions contract
private val requestMultiplePermissions =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions : Map<String, Boolean> ->
        // Do something if some permissions granted or denied
        permissions.entries.forEach {
            // Do checking here
        }                                                                             
}

最后

在这里插入图片描述
通过对比可以清楚看到Result API好处:通过ActivityResultContract避免了对requestCode、onActivityResult的感知,减少了模板代码。更重要的是多种预置ActivityResultContract,极大降低了系统API的通信成本,为日常开发提供了便利,是时候跟startActivityForResult说再见了!

目录
相关文章
|
6月前
|
网络协议 API
Posix API与网络协议栈实现原理
Posix API与网络协议栈实现原理
51 0
|
6月前
|
存储 缓存 网络协议
posix API与网络协议栈的实现原理
posix API与网络协议栈的实现原理
|
6月前
|
网络协议 Unix Linux
Posix API与网络协议栈实现原理
Posix API与网络协议栈实现原理
|
6月前
|
网络协议 API 网络性能优化
Posix API与网络协议栈的实现原理
Posix API与网络协议栈的实现原理
57 0
|
API Android开发
Android Activity Result API
Android Activity Result API
154 0
|
分布式计算 Java API
Flink相关API开发及运行架构和实现原理详解
Flink相关API开发及运行架构和实现原理详解
314 0
Flink相关API开发及运行架构和实现原理详解
|
9天前
|
供应链 数据挖掘 API
电商API接口介绍——sku接口概述
商品SKU(Stock Keeping Unit)接口是电商API接口中的一种,专门用于获取商品的SKU信息。SKU是库存量单位,用于区分同一商品的不同规格、颜色、尺寸等属性。通过商品SKU接口,开发者可以获取商品的SKU列表、SKU属性、库存数量等详细信息。
|
10天前
|
JSON API 数据格式
店铺所有商品列表接口json数据格式示例(API接口)
当然,以下是一个示例的JSON数据格式,用于表示一个店铺所有商品列表的API接口响应
|
20天前
|
编解码 监控 API
直播源怎么调用api接口
调用直播源的API接口涉及开通服务、添加域名、获取API密钥、调用API接口、生成推流和拉流地址、配置直播源、开始直播、监控管理及停止直播等步骤。不同云服务平台的具体操作略有差异,但整体流程简单易懂。
|
1月前
|
人工智能 自然语言处理 PyTorch
Text2Video Huggingface Pipeline 文生视频接口和文生视频论文API
文生视频是AI领域热点,很多文生视频的大模型都是基于 Huggingface的 diffusers的text to video的pipeline来开发。国内外也有非常多的优秀产品如Runway AI、Pika AI 、可灵King AI、通义千问、智谱的文生视频模型等等。为了方便调用,这篇博客也尝试了使用 PyPI的text2video的python库的Wrapper类进行调用,下面会给大家介绍一下Huggingface Text to Video Pipeline的调用方式以及使用通用的text2video的python库调用方式。

热门文章

最新文章