Android Developer
Android Developer

Reputation: 9665

Creating an intent inside child activity rather than parent activity while starting an activity

What is the difference in terms of perfomance and optimization if while starting an activity i create an intent inside Child Activity(Activity to be started) rather than in parent Activity(Activity which is starting an new activity).

Example-

ChildActivity.class

public static Intent createIntent(Context context) {
    return new Intent(context, ChildActivity.class);
}

ParentActivity.class

     startActivity(ChildActivity.createIntent(ParentActivity.this));

Is it a good practice?Will this approach have any advantage if same activity is being started from multiple activities?

Upvotes: 0

Views: 587

Answers (1)

Norutan
Norutan

Reputation: 1520

We can use that practice, so that we can start an Activity from any activities by calling a static method, we will save a lot of duplicate code. For me, I create a Navigator class, this class will store all methods which start activity:

public class Navigator {
    public static final String VENUE_EXTRA = "venue_extra";

    private Navigator() {

    }

    public static void navigateToOnboarding(Activity activity) {
        Intent intent = new Intent(activity, OnboardingActivity.class);
        ActivityCompat.startActivity(activity, intent, null);
    }

    public static void navigateToSharing(Activity activity, Venue venue) {
        Intent intent = new Intent(activity, SharingActivity.class);
        intent.putExtra(VENUE_EXTRA, venue);
        ActivityCompat.startActivity(activity, intent, null);
    }

    public static void navigateToAppSetting(Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        activity.startActivity(intent);
    }
}

Upvotes: 1

Related Questions