Skip to content

🐨 Simple Activity Result API with Kotlin Coroutines

License

Notifications You must be signed in to change notification settings

7hens/activity-request

Repository files navigation

Activity Request

jitpack license

Activity的启动变得如此简单。

启动 Activity

suspend fun startActivitySample(context: Context) {
    // 这里的 context 参数甚至可以传 applicationContext
    val (code, data) = MyActivity.startForResult(context)

    when (code) {
        Activity.RESULT_OK -> {}
        Activity.RESULT_CANCELED -> {}
    }
}

请求动态权限

private suspend fun requestPermissionsSample(context: Context) {
    val storagePermission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE

    // 这里的 context 参数甚至可以传 applicationContext
    val isGranted = AndroidPermissions.request(context, storagePermission)
}

使用带参数的 Intent

MyActivity.start(context) {
    it.actionName = "foobar"
    it.hello = false
}
class MyActivity: Activity() {
    // 这是固定写法,必须实现 ActivityIntentCompanion<Companion>
    companion object: ActivityIntentCompanion<Companion> {
        var Intent.actionName by string()
        var Intent.hello by boolean()
        var Intent.activityInfo by parcelable<ActivityInfo>()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 获取 intent 的参数
        // intent.actionName
        // intent.hello
        // intent.activityInfo
    }
}

添加依赖

implementation("com.github.7hens.activity-request:activity-request-core:$latest_version")
implementation("com.github.7hens.activity-request:activity-request-extra:$latest_version")

latest_version: jitpack