A Better Way to Launch Activities on Android
Single Responsibility + Kotlin!
Launching an Activity
with Intent
arguments is not a developer friendly experience. The major pain points are:
- Argument Serialization:
intent.putExtra(key, value)
- Argument Deserialization:
intent.getStringExtra(key)
- Type safety, Maintainability, and Testing
What if there was a better way? Like many issues with the Android framework, we can fix this with a combination of single responsibility and dependency injection. Given the following scenario, let’s create an ideal API to illustrate.
Scenario
Build an API to launch a MediumProfileActivity
that displays the following information:
Three pieces of information will be needed to render the user interface above:
Creating the API
Now, let’s imagine an ideal, developer-friendly API to serialize our arguments and launch a MediumProfileActivity
. It may look something like this:
Inside a MediumProfileActivity
, we will need to deserialize our arguments to access them later.
Notice no messy intent.putExtra(key, value)
or intent.getStringExtra(key)
code pollution. Kotlin’s lazy
delegate makes this even cleaner.
We’ll use an ActivityArgs
interface to give common functionality to all our implementations.
This enables us to directly .launch()
into an Activity
, or use args.intent()
to pass around an intent for that Activity
.
Flexible!
Next, we must implement ActivityArgs
in a MediumProfileActivityArgs
. This will require a strategy for serialization (intent.putExtra()
) and a strategy for deserialization (intent.getExtra()
).
Boom! We have a solution that is easily maintained — there’s one class that handles serializing and deserializing arguments for the MediumProfileActivity
.
What about testing?
Super easy. Four steps.
- Create your
MediumProfileActivityArgs
instance. - Serialize instance into an
Intent
. - Deserialize that
intent
. - Verify de-serialized
Args
are equal to the originalArgs
.
See the example below:
Conclusion
I firmly believe the above is a better approach to launching an Activity
than the traditional YourActivity.launch(param1, param2)
approach, which falls short in three ways:
- No deserialization. Requires additional code in
onCreate()
to deserialize (intent.getStringExtra()
). - Inflexible. What if you want an
intent
instance? You’d have add an overloaded method —YourActivity.intent(param1, param2)
. WithActivityArgs
, just callargs.intent()
. - Harder to test. You would have to launch an activity to test deserialization
I hope ActivityArgs
improves your development experience!
Full code on GitHub.
Follow me on Twitter! @zaktaccardi
Catch the conversation on reddit
DISCLOSURE STATEMENT: These opinions are those of the author. Unless noted otherwise in this post, Capital One is not affiliated with, nor is it endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are the ownership of their respective owners. This article is © 2018 Capital One.