Wednesday, March 31, 2010

Android Utility class - Activity navigation.

In this article helps to create and use the utility class for activity navigation.

1. Create a normal class
    public class ActivityHelper { }

2. Define the utility method using the static factory method
    1. public static Intent createActivityIntent(Activity activity,Class preconditionActivityClazz) { } -used to create a intent       
    2. public static void startOriginalActivityAndFinish(Activity preconditionActivity) { } - Return to the old activity
    3. public static void startNewActivityAndFinish(Activity activity,Intent intent) { } - Finish the current Activty and start a new activity.    

3. Implementation
    Intent intent = ActivityHelper.createActivityIntent(MainActivity.this,TargetActivity.class);   
    Using this intent we can navigate the screen
    startNewActivityAndFinish(intent); -> now the Activity moves to the TargetActivity and close the current activty.
    startOriginalActivityAndFinish(TargetActivity.this); - Return back to orginal activity.

Sample Code
public class ActivityHelper {
    static private final String EXTRA_WRAPPED_INTENT = "ActivityHelper_wrappedIntent";
     * Create a precondition activity intent.
     * @param activity the original activity
     * @param preconditionActivityClazz the precondition activity's class
     * @return an intent which will launch the precondition activity.
    public static Intent createActivityIntent(Activity activity,
            Class preconditionActivityClazz) {
        Intent newIntent = new Intent();
        newIntent.setClass(activity, preconditionActivityClazz);
        newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent());
        return newIntent;

     * Start the original activity, and finish the precondition activity.     
     * @param preconditionActivity
    public static void startOriginalActivityAndFinish(
            Activity preconditionActivity) {
        preconditionActivity.startActivity((Intent) preconditionActivity.getIntent().getParcelableExtra(EXTRA_WRAPPED_INTENT));


     * Start the precondition activity using a given intent, which should have
     * been created by calling createPreconditionIntent.
     * @param activity
     * @param intent
    public static void startNewActivityAndFinish(Activity activity,
            Intent intent) {


No comments:

Post a Comment