ActivityResult的优雅实现

我们都知道在Android中使用startActivityForResult打开一个新的活动,并得到返回值。但这种方式存在一定的局限性,需要在一个Activity或者Fragment中才能实现。有的时候代码架构的不同,可能这种方式并不能满足我们的需要。比如在Adapter中实现跳转等。下面提供一个优雅的方式,使得发起和获取结果在同一处。便于我们操作。

提供一个可观察的ActivityResult,并在订阅的时候,将结果全部发射出去

class ActivityResultObservable<T> private constructor(private val subscribe: (ActivityResultCreateEmitter<T>) -> Unit) {

companion object {
@JvmStatic
fun <T> create(subscribe: (ActivityResultCreateEmitter<T>) -> Unit): ActivityResultObservable<T> = ActivityResultObservable(subscribe)
}

fun subscribe(onSuccess: (data: T) -> Unit) = subscribe(ActivityResultObserver(onSuccess = onSuccess))

fun subscribe(onSuccess: (data: T) -> Unit, onCanceled: () -> Unit) = subscribe(ActivityResultObserver(onSuccess = onSuccess, onCanceled = onCanceled))

fun subscribe(onSuccess: (data: T) -> Unit, onCanceled: () -> Unit, onDefined: (resultCode: Int, data: T?) -> Unit) =
subscribe(ActivityResultObserver(onSuccess = onSuccess, onCanceled = onCanceled, onDefined = onDefined))

fun subscribe(onBefore: () -> Unit,
onSuccess: (data: T) -> Unit,
onCanceled: () -> Unit,
onDefined: (resultCode: Int, data: T?) -> Unit) =
subscribe(ActivityResultObserver(onBefore, onSuccess, onCanceled, onDefined))

fun subscribe(observer: ActivityResultObserver<T>) {
val emitter = ActivityResultCreateEmitter(observer)
subscribe.invoke(emitter)
}
}

class ActivityResultCreateEmitter<T>(private val activityResultObserver: ActivityResultObserver<T>) {

/**
* this method invoke after onActivityResult, before [onSuccess] [onCanceled] [onDefined]
*/
fun onBefore() = activityResultObserver.onBefore.invoke()

fun onSuccess(data: T) = activityResultObserver.onSuccess.invoke(data)

fun onCanceled() = activityResultObserver.onCanceled.invoke()

fun onDefined(resultCode: Int, data: T?) = activityResultObserver.onDefined.invoke(resultCode, data)
}

class ActivityResultObserver<T>(val onBefore: () -> Unit = {},
val onSuccess: (T) -> Unit = {},
val onCanceled: () -> Unit = {},
val onDefined: (Int, T?) -> Unit = { _, _ -> })

object ActivityResultUtil {
private val codeGenerator = Random()

fun <M : Map<Int, *>> generateRequestCode(map: M): Int {
var requestCode: Int
do {
requestCode = codeGenerator.nextInt(0xFFFF)
} while (requestCode in map.keys)
return requestCode
}
}

通过对Activity和Fragment中提供扩展方法startActivityForResult(Intent,Bundle),返回一个ActivityResultObservable的对象。

private const val FRAGMENT_TAG = "ActivityResultHelper_ActivityResultExecuteFragment_Tag"
private val resultHolder = LinkedHashMap<Int, ActivityResultCreateEmitter<Intent>>()

private fun getExecuteFragment(manager: android.app.FragmentManager): ActivityResultExecuteFragment {
return manager.findFragmentByTag(FRAGMENT_TAG) as? ActivityResultExecuteFragment
?: ActivityResultExecuteFragment().also {
manager.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
beginTransaction().replace(android.R.id.content, it, FRAGMENT_TAG).commitNowAllowingStateLoss()
} else {
beginTransaction().replace(android.R.id.content, it, FRAGMENT_TAG).commitAllowingStateLoss()
executePendingTransactions()
}
}
}
}

private fun getSupportExecuteFragment(manager: FragmentManager): ActivityResultSupportExecuteFragment {
return manager.findFragmentByTag(FRAGMENT_TAG) as? ActivityResultSupportExecuteFragment
?: ActivityResultSupportExecuteFragment().also {
manager.beginTransaction().replace(android.R.id.content, it, FRAGMENT_TAG).commitNowAllowingStateLoss()
}
}

fun <A : FragmentActivity> A.startActivityForResult(intent: Intent, options: Bundle? = null): ActivityResultObservable<Intent> {
//获取一个与已有编码不重复的编码
val requestCode = ActivityResultUtil.generateRequestCode(resultHolder)
//获取或创建SupportExecuteFragment
val executeFragment = getSupportExecuteFragment(supportFragmentManager)
//调用Fragment的startActivityForResult方法
return executeFragment.startActivityForResult(requestCode, intent, options)
}

fun <A : Activity> A.startActivityForResult(intent: Intent, options: Bundle? = null): ActivityResultObservable<Intent> {
if (this is FragmentActivity) {
return (this as FragmentActivity).startActivityForResult(intent, options)
}
//获取一个与已有编码不重复的编码
val requestCode = ActivityResultUtil.generateRequestCode(resultHolder)
//获取或创建ExecuteFragment
val executeFragment = getExecuteFragment(fragmentManager)
//调用Fragment的startActivityForResult方法
return executeFragment.startActivityForResult(requestCode, intent, options)
}

fun <F : Fragment> F.startActivityForResult(intent: Intent, options: Bundle? = null): ActivityResultObservable<Intent> {
//获取一个与已有编码不重复的编码
val requestCode = ActivityResultUtil.generateRequestCode(resultHolder)
//获取或创建SupportExecuteFragment
val executeFragment = getSupportExecuteFragment(activity!!.supportFragmentManager)
//调用Fragment的startActivityForResult方法
return executeFragment.startActivityForResult(requestCode, intent, options)
}

fun <F : android.app.Fragment> F.startActivityForResult(intent: Intent, options: Bundle? = null): ActivityResultObservable<Intent> {
if (this is Fragment) {
return (this as Fragment).startActivityForResult(intent, options)
}
//获取一个与已有编码不重复的编码
val requestCode = ActivityResultUtil.generateRequestCode(resultHolder)
//获取或创建ExecuteFragment
val executeFragment = getExecuteFragment(activity.fragmentManager)
//调用Fragment的startActivityForResult方法
return executeFragment.startActivityForResult(requestCode, intent, options)
}

internal class ActivityResultSupportExecuteFragment : Fragment() {

init {
retainInstance = true
}

internal fun startActivityForResult(requestCode: Int, intent: Intent, options: Bundle? = null): ActivityResultObservable<Intent> {
return ActivityResultObservable.create {
resultHolder[requestCode] = it
startActivityForResult(intent, requestCode, options)
}
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//取出与requestCode对应的对象,然后执行与resultCode对应的回调
resultHolder.remove(requestCode)?.let {
it.onBefore()
when (resultCode) {
FragmentActivity.RESULT_OK -> it.onSuccess(data ?: Intent())
FragmentActivity.RESULT_CANCELED -> it.onCanceled()
else -> it.onDefined(resultCode, data)
}
}
}
}

internal class ActivityResultExecuteFragment : android.app.Fragment() {

init {
retainInstance = true
}

internal fun startActivityForResult(requestCode: Int, intent: Intent, options: Bundle? = null): ActivityResultObservable<Intent> {
return ActivityResultObservable.create {
resultHolder[requestCode] = it
startActivityForResult(intent, requestCode, options)
}
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//取出与requestCode对应的对象,然后执行与resultCode对应的回调
resultHolder.remove(requestCode)?.let {
it.onBefore()
when (resultCode) {
FragmentActivity.RESULT_OK -> it.onSuccess(data ?: Intent())
FragmentActivity.RESULT_CANCELED -> it.onCanceled()
else -> it.onDefined(resultCode, data)
}
}
}

startActivityForResult(Intent(Intent.ACTION_GET_CONTENT).apply {
addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
type = MiddleWareConst.IMAGE_TYPE
}).subscribe(onSuccess = {
//成功回调
}, onCanceled = {
//取消回调
}, onDefined = { _: Int, _: Intent? ->
//自定义code回调
})

可以看出该方法最大的好处就是调用的和回调的地方在一起,不需要自己通过onActivityResult来分发,且该实现方式侵入性很低,不需要额外提供Rxjava等第三方库。

原创:https://www.panoramacn.com
源码网提供WordPress源码,帝国CMS源码discuz源码,微信小程序,小说源码,杰奇源码,thinkphp源码,ecshop模板源码,微擎模板源码,dede源码,织梦源码等。

专业搭建小说网站,小说程序,杰奇系列,微信小说系列,app系列小说

ActivityResult的优雅实现

免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。

您必须遵守我们的协议,如果您下载了该资源行为将被视为对《免责声明》全部内容的认可-> 联系客服 投诉资源
www.panoramacn.com资源全部来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。 敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:2640602276@qq.com
未经允许不得转载:书荒源码源码网每日更新网站源码模板! » ActivityResult的优雅实现
关注我们小说电影免费看
关注我们,获取更多的全网素材资源,有趣有料!
120000+人已关注
分享到:
赞(0) 打赏

评论抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

您的打赏就是我分享的动力!

支付宝扫一扫打赏

微信扫一扫打赏