1 package com.android.onboarding.contracts
2
3 import android.content.Context
4 import android.content.Intent
5 import android.os.Bundle
6 import androidx.activity.ComponentActivity
7 import androidx.activity.result.ActivityResultCallback
8 import androidx.activity.result.ActivityResultLauncher
9 import com.google.errorprone.annotations.CanIgnoreReturnValue
10
11 /** A wrapper around a request to launch a particular activity via a contract. */
12 open class ActivityLauncher<I>
13 internal constructor(protected val context: Context, protected open val contract: Launchable<I>) {
14 /** Prepares an intent from supplied [args] with the intention of launching it immediately. */
prepareIntentnull15 protected open fun prepareIntent(args: I): Intent =
16 contract.launcher.createIntentDirectly(context, args)
17
18 @CanIgnoreReturnValue
19 fun launch(args: I): NodeId {
20 val intent = prepareIntent(args)
21 context.startActivity(intent)
22 return intent.getLongExtra(EXTRA_ONBOARDING_NODE_ID, UNKNOWN_NODE_ID)
23 }
24
25 /** Launches an activity with given [flags] and contract arguments [args]. */
26 @CanIgnoreReturnValue
launchnull27 fun launch(args: I, flags: Int): NodeId {
28 val intent = prepareIntent(args).apply { this.flags = flags }
29 context.startActivity(intent)
30 return intent.getLongExtra(EXTRA_ONBOARDING_NODE_ID, UNKNOWN_NODE_ID)
31 }
32
33 @CanIgnoreReturnValue
launchnull34 fun launch(args: I, options: Bundle?): NodeId {
35 val intent = prepareIntent(args)
36 context.startActivity(intent, options)
37 return intent.getLongExtra(EXTRA_ONBOARDING_NODE_ID, UNKNOWN_NODE_ID)
38 }
39 }
40
41 /** Equivalent to [ComponentActivity.registerForActivityResult] when a result is not expected. */
registerForActivityLaunchnull42 fun <I> Context.registerForActivityLaunch(contract: Launchable<I>) =
43 ActivityLauncher(this, contract)
44
45 /** Wrapper over [ComponentActivity.registerForActivityResult] for [LaunchableForResult]. */
46 fun <I, O> ComponentActivity.registerForActivityResult(
47 contract: LaunchableForResult<I, O>,
48 callback: ActivityResultCallback<O>,
49 ): ActivityResultLauncher<I> =
50 registerForActivityResult(contract.launcher.toActivityResultContract(), callback)
51