ActivityResultAPI使⽤与源码分析,android插件化原理
Activity注册这个观察者
var myLifecycleObserver=MyLifecycleObserver(registry = activityResultRegistry)
lifecycle.addObserver(myLifecycleObserver)
调⽤
myLifecycleObserver.selectImage()
实现DefaultLifecycleObserver,在onCreate注册协定
class MyLifecycleObserver(private val registry : ActivityResultRegistry) :DefaultLifecycleObserver{
lateinit var getContent : ActivityResultLauncher
override fun onCreate(owner: LifecycleOwner) {
getContent = ister(“key”, owner, ActivityResultContracts.GetContent(),
ActivityResultCallback { log(it) })
}
fun selectImage(){
getContent.launch(“image/*”)
}
}
⼆,源码
使⽤版本activity-ktx:1.2.2,fragment-ktx:1.3.3
registerForActivityResult⽅法最终会调⽤ActivityResultRegistry的 register⽅法,通过不同的key⽣成⼀个唯⼀的requestCode,把这
个requestCode保存下来,在结果返回时使⽤。通过Lifecycle添加⼀个观察者,监听Activity的ON_START,ON_STOP,ON_DESTROY事件。在ON_START事件到来时,会从mPendingResults这个bundle对象中通过key获取结果,如果有结果,则将结果回调到调⽤者
处。ON_STOP事件则是移除这个key对应的CallbackAndContract对象,ON_DESTROY事件移除这个key对应的所有信息。最后返
回ActivityResultLauncher对象给调⽤者使⽤。
public final <I, O> ActivityResultLauncher register(
@NonNull final String key,
@NonNull final LifecycleOwner lifecycleOwner,
@NonNull final ActivityResultContract<I, O> contract,
@NonNull final ActivityResultCallback callback) {
Lifecycle lifecycle = Lifecycle();
/
/每个请求的key也不⼀样,根据key⽣成⼀个唯⼀的requestCode
final int requestCode = registerKey(key);
//把lifecycle和observer统⼀封装到LifecycleContainer中
LifecycleContainer lifecycleContainer = (key); if (lifecycleContainer == null) {
lifecycleContainer = new LifecycleContainer(lifecycle);
}
LifecycleEventObserver observer = new LifecycleEventObserver() {
register for@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));
if (ainsKey(key)) {
@SuppressWarnings(“unchecked”)
final O parsedPendingResult = (O) (key); ve(key);
}
//从bundle中获取结果
final ActivityResult pendingResult = Parcelable(key);
if (pendingResult != null) {
//把结果回调给调⽤者
}
} else if (Lifecycle.Event.ON_STOP.equals(event)) {
} else if (Lifecycle.Event.ON_DESTROY.equals(event)) {
unregister(key);//destory时注销
}
}
};
//添加观察者
lifecycleContainer.addObserver(observer);
mKeyToLifecycleContainers.put(key, lifecycleContainer);
//返回ActivityResultLauncher对象
return new ActivityResultLauncher() {
@Override
public void launch(I input, @Nullable ActivityOptionsCompat options) {
mLaunchedKeys.add(key);
//ActivityResultRegistry的onLaunch,抽象⽅法,在ComponentActivity内实现
onLaunch(requestCode, contract, input, options);
}
public void unregister() {
ActivityResultRegistry.this.unregister(key);
}
public ActivityResultContract<I, ?> getContract() {
return contract;
}
};
}
2.launch
ActivityResultRegistry的onLaunch是⼀个抽象⽅法,在ComponentActivity内实现。⾸先会检查contra
ct是否能获取同步结果,如果能,则直接分发处理。⽐如权限申请,我前⾯已经获取了权限,直接可以通过getSynchronousResult查询是否有权限。有直接返回true,不再通
过requestPermissions去做申请权限。
在通过contract获取Intent,按Intent分为三种情况处理,第⼀种,权限申请,通过requestPermissions去申请权限,第⼆种处
理INTENT_SENDER,和startIntentSenderForResult类似。第三种,处理其它问题,通过startActivityForResult启动Activity
public <I, O> void onLaunch(
final int requestCode,
@NonNull ActivityResultContract<I, O> contract,
I input,
@Nullable ActivityOptionsCompat options) {
ComponentActivity activity = ComponentActivity.this;
//如果能直接拿到结果,直接分发处理了。
final ActivityResultContract.SynchronousResult synchronousResult =
if (synchronousResult != null) {
new MainLooper()).post(new Runnable() {
@Override
public void run() {
dispatchResult(requestCode, Value());
}
});
return;
}
// 根据协定创建Intent对象
Intent intent = ateIntent(activity, input);
Bundle optionsBundle = null;
// If there are any extras, we should defensively set the classLoader
if (Extras() != null && Extras().getClassLoader() == null) { intent.ClassLoader());
}
if (intent.hasExtra(EXTRA_ACTIVITY_OPTIONS_BUNDLE)) {
optionsBundle = BundleExtra(EXTRA_ACTIVITY_OPTIONS_BUNDLE); veExtra(EXTRA_ACTIVITY_OPTIONS_BUNDLE);
} else if (options != null) {
optionsBundle = Bundle();
}
//处理权限
if (ACTION_REQUEST_PERMISSIONS.Action())) {
// requestPermissions path
String[] permissions = StringArrayExtra(EXTRA_PERMISSIONS);
if (permissions == null) {
permissions = new String[0];
}
} else if (ACTION_INTENT_SENDER_REQUEST.Action())) {
//处理StartIntentSenderForResult
IntentSenderRequest request =
try {
// startIntentSenderForResult path
ActivityCompat.startIntentSenderForResult(activity, IntentSender(),
requestCode, FillInIntent(), FlagsMask(),
} catch (final IntentSender.SendIntentException e) {
}
} else {
//其它普通问题启动Activity
ActivityCompat.startActivityForResult(activity, in
《Android学习笔记总结+最新移动架构视频+⼤⼚安卓⾯试真题+项⽬实战源码讲义》
【docs.qq/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
tent, requestCode, optionsBundle);
}
}
3.结果回调
在ComponentActivity中,onActivityResult和onRequestPermissionsResult⽅法会先被ActivityResultRegistry的dispatchResult⽅法拦截,如果它能处理,则不再调⽤Activity的⽅法。
dispatchResult会调⽤doDispatch来处理结果,这有两种情况,通过key从mKeyToCallback中获取callbackAndContract对象,如果不为空,则直接回调结果。⽐如权限申请,不会⾛ON_STOP事件,mKeyToCallback不会被清除,这⾥就不会为空。如果为空则把结果放
到mPendingResults这个Bundle对象中,和前⾯的ON_START事件对应起来,从mPendingResults取出结果,回调结果。
-ComponentActivity.java
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (!mActivityResultRegistry.dispatchResult(requestCode, resultCode, data)) {
}
}
public void onRequestPermissionsResult(
int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
if (!mActivityResultRegistry.dispatchResult(requestCode, Activity.RESULT_OK, new Intent()
.putExtra(EXTRA_PERMISSIONS, permissions)
.putExtra(EXTRA_PERMISSION_GRANT_RESULTS, grantResults))) {
if (Build.VERSION.SDK_INT >= 23) {
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。