Android pattern to start new activity

In this short blog post, I’ll write about a pattern I like to use when starting new activities in Android development.

To start a new activity in Android development, we need to instantiate an intent, specify in that intent the current activity’s name and the new activity’s name. The code usually looks something like this.

This is pretty common and straightforward. The one thing I never really liked about this though, especially if the ToActivity is an activity that’s called often from different places, is how I always have to manually instantiate a new intent and then specify which activity I am trying to open.

Instead of manually instantiating a new intent in an Activity file every time I want to open a new intent, I like to set a static method on the Activity class that needs to be opened. For example, in our example, in our ToActivity class file, I would have a static method called startActivity that looks like this.

And then in our original code to open our new activity, we would write it like this

I find this to be much cleaner compared to our previous version. Also, if we need to start up ToActivity from more than one place, this pattern allows us to reuse the startActivity method, thus reducing duplication.