Any benefit from starting activity through intent one way versus the other?
I know two ways to get started with intent. Let me say that I am in Activity A and I want to start Activity B. I could do the following.
1) In Activity B, I have a 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) Another method is the one I see more often:
From action A I will do the following
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
Are there any advantages or disadvantages to using one or the other? I think method 1 is a bit clean, because it stores the intent information in the class to be actually run with the intent.
source to share
first case
Pros:
- This follows a principle
DRY
that does not repeat itself.
Minuses:
-
It is limited to only one class ie
ActivityB.class
-
Fuzzy naming convention for the Utility class
-
Note the flexibility to add additional properties if the method definition is not changed to accept some
map
or something
Second case
Pros:
-
More flexible as any action can be triggered
-
Any attribute can be added to
intent
the ig objectputExtra
and so many others
Minuses:
-
Doesn't follow DRY principles
-
Ineffective when duplicated many times
Improvements
- Give the correct name to your method.
- Can be overloaded to accept a card for key value
- Apply
Class<?>
to accept any class as a parameter
source to share
Both approaches do the same.
I think the first approach is really easier to understand and it is less code. But I think most people are used to the second approach and might be a little embarrassed to see it this way. This disadvantage is not that significant, although I don't think so.
The point is, if you are using the first approach, you still need to use the second approach if you want to start work that you did not create, because you cannot just add a static method to an already compiled one. class file. This can make your code a little inconsistent.
Also, the name newIntent
is confusing. I don't know, it's just me, but doesn't it look like you are moving from Activity B to A? Maybe simple intent
?
source to share