ActivityResult的优雅实现

   日期:2020-10-03     浏览:91    评论:0    
核心提示:我们都知道在Android中使用startActivityForResult打开一个新的活动,并得到返回值。但这种方式存在一定的局限性,需要在一个Activity或者Fragment中才能实现。有的时候代码架构的不同,可能这种方式并不能满足我们的需要。比如在Adapter中实现跳转等。下面提供一个优雅的方式,使得发起和获取结果在同一处。便于我们操作。提供一个可观察的ActivityResult,并在订阅的时候,将结果全部发射出去class ActivityResultObservable<T>

我们都知道在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>) { 

    
    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等第三方库。

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服