A better way to launch Activities

This is how we used to launch an Activity

Intent it = new Intent(MainActivity.this,NormalActivity.class);
it.putExtra("key1","val1");
it.putExtra("key2","val2");
startActivity(it);Code language: JavaScript (javascript)

Have you ever thought about this: not every Activity is developed by your team.

In that case, if you want to launch another Activity, you may need to ask the developer responsible for that Activity or check its documentation.

But isn’t this pretty cumbersome?

Is there a better solution?

What if we hand over the Activity launch logic to another developer?

Meaning, the creator of each Activity adds a method inside that Activity. Other developers can call this method to start the Activity.

Intent it = new Intent(MainActivity.this,NormalActivity.class);
it.putExtra("site","www.foxdevelop.com");//Launch another Activity from our own Activity
//We need to know what data the other Activity expects, so we have to coordinate with that Activity's developer
startActivity(it);Code language: JavaScript (javascript)

Let’s try this. We’ll add a static method inside the target Activity.

//Put the Activity launch code inside the target Activity class
public static void actionStart(Context context, String site, int level)
{
    Intent it = new Intent(context,NormalActivity.class);
    it.putExtra("site",site);
    it.putExtra("level",level);
    context.startActivity(it);
}Code language: JavaScript (javascript)
NormalActivity.actionStart(MainActivity.this,"www.foxdevelop.com",12);Code language: CSS (css)

A better way to launch Activities

Leave a Reply

Your email address will not be published. Required fields are marked *