ActivityResult的優雅實現

2020-10-03 12:01:05

我們都知道在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等第三方庫。