or how to do something different

One of the very first things I do when I started an Android project is to create an IntentFactory class to handle the creation of the intents for each activity.

Simple explanation of IntentFactory

Let’s imagine we have the following Activity:

public class MyActivity extends Activity {

public static final String PARAM1_KEY = "param1";

private String param1; @Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

param1 = getIntent().getStringExtra(PARAM1_KEY); // Blah blah

}

}

As you can see, MyActivity has a mandatory param1 “parameter”. How to make sure the caller sends this parameter? Well, IntentFactory to the rescue!

We create an IntentFactory with the following method:

public class IntentFactory { public Intent newMyActivityIntent(Context ctx, String param1) {

final Intent intent = new Intent(ctx, MyActivity.class);

intent.putExtra(PARAM1_KEY, param1);

return intent;

}

}

We can even make things a bit nicer in the Activity using Dart. Dart is:

Extra “injection” library for Android which uses annotation processing to generate code that does direct field assignment of your extras.

Our final MyActivity will end up looking like this:

public class MyActivity extends Activity {

public static final String PARAM1_KEY = "param1";

@InjectExtra(PARAM1_KEY) String param1; @Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Dart.inject(this); // Blah blah

}

}

Cons of using IntentFactory

Although using an IntentFactory is much better than letting the caller create the intent on their own, there are some cons of using it:

Violates the Open/closed principle

Big apps end up having a HUGE class

class How to deal with optional parameters? Should we pass the optional parameter to the IntentFactory’s method as null?

More than one method to call a single activity

I can’t remember of anything else at the moment :)

Replacing the IntentFactory with something else

The activity is the one who knows which parameter is mandatory and which is optional. Wouldn’t be nice that each activity knows how to create their intent? We can use the builder pattern to create the intent. We can do it manually or, taking advantage of Dart’s information, create an annotation processing library that does the work for us.