Android Friday: Let Activities encapsulate their creation

Opening screens from other screens in Android apps is straight forward: create an Intent object, stuff some parameters into it, use it to launch the other Activity, and dig out the passed parameters at the other end.

Unfortunately, if you blindly follow Googles standard examples of how to do this, you will end up sprinkling potential bugs around your codebase. Let’s look at how to tighten it up a bit.

In basic Android apps, each distinct screen you see is usually backed by an Activity class. In our case, we have ProfileActivity backing a profile screen:

This is fine if ProfileActivity is just launched from this one place. But if we do this from a bunch of different places in our app, it will feel somewhat clunky. Why should any other Activities even know about the details of how ProfileActivity is launched — why not let it handle that itself?