intA
intA

Reputation: 2701

Any benefit to starting an Activity via an intent one way versus another?

I know of two ways to start an Activity with an intent. Let's say I'm in Activity A and I want to start Activity B. I could do the following.

1) In Activity B I have some static method:

public static Intent newIntent(Context packageContext){
    Intent intent = new Intent(packageContext, ActivityB.class);
    return intent;
}

And from Activity A I can call:

startActivity(ActivityB.newIntent(this));

2) The other method is the one I see more often:

From Activity A I do the following

Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);

Are there any benefits or drawbacks to using one versus the other? I think method 1 is a bit cleaner because it keeps the intent information in the class that will actually be started with the intent.

Upvotes: 3

Views: 154

Answers (2)

Sweeper
Sweeper

Reputation: 274520

The two approaches do exactly the same thing.

I think the first approach is indeed easier to understand and it's less code. But I think most people got used to the second approach and might be a little confused when they see it like that. This drawback isn't that significant though I don't think.

The thing is, if you use the first approach, you still need to use the second approach if you want to start an activity that you didn't create because you can't just add a static method to an already compiled .class file. This might make your code a little inconsistent.

Also, the name newIntent is kind of confusing. I don't know if it's just me, but doesn't it sound a bit like that you are going from Activity B to A? Maybe just intent?

Upvotes: 1

Pavneet_Singh
Pavneet_Singh

Reputation: 37414

case first

Pros :

  • This follows the DRY principle mean don't repeat your self

Cons :

  • It is only limited to one class i.e ActivityB.class

  • Unclear naming convention for a Utility class

  • Note flexible to add extra properties unless method definition is modified to accept some map or something

Second case

Pros:

  • More flexible as any activity can be started

  • Any attribute can be added to intent object i.g putExtra and so many other

Cons :

  • Does not follow the DRY principle

  • Inefficient when duplicated many times

Improvements

  • Give your method proper naming
  • Can be overloaded to accept a map for key-value
  • Apply Class<?> to accept any class as parameter

Upvotes: 1

Related Questions