Starter Pattern

suggest change

This pattern is a more strict approach to starting an Activity. Its purpose is to improve code readability, while at the same time decrease code complexity, maintenance costs, and coupling of your components.

The following example implements the starter pattern, which is usually implemented as a static method on the Activity itself. This static method accepts all required parameters, constructs a valid Intent from that data, and then starts the Activity.

An Intent is an object that provides runtime binding between separate components, such as two activities. The Intent represents an app’s “intent to do something.” You can use intents for a wide variety of tasks, but here, your intent starts another activity.

public class ExampleActivity extends AppCompatActivity {

    private static final String EXTRA_DATA = "EXTRA_DATA";

    public static void start(Context context, String data) {
        Intent intent = new Intent(context, ExampleActivity.class);
        intent.putExtra(EXTRA_DATA, data);
        context.startActivity(intent);
    }       

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        if(!intent.getExtras().containsKey(EXTRA_DATA)){
            throw new UnsupportedOperationException("Activity should be started using the static start method");
        }
        String data = intent.getStringExtra(EXTRA_DATA);
    }
}

This pattern also allows you to force additional data to be passed with the intent.

The ExampleActivity can then be started like this, where context is an activity context:

ExampleActivity.start(context, "Some data!");

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents