Ajay Shrestha
Ajay Shrestha

Reputation: 2455

What is the difference between getIntent() and new Intent() in Android?

I do like this

first way

Intent intent = new Intent();
intent.putExtra("isLoggedIn",true);
setResult(RESULT_OK,intent);

second way

Intent intent = getIntent();
intent.putExtra("isLoggedIn",true);
setResult(RESULT_OK,intent);

Both can give the same result.I want to know the actual difference between this two

Upvotes: 1

Views: 1384

Answers (1)

Tamby Kojak
Tamby Kojak

Reputation: 2159

In the context of an Activity, getIntent() will return the Intent that was originally sent to the Activity. The example you gave may work the same, but you should really avoid using getIntent() if you are passing the Intent to another Activity or sending it back as a result.

For example:

If I start an activity with:

Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", "test");
startActivity(intent);

Then in my MainActivity class:

Intent intent = getIntent();
String value = intent.getString("key"); // value will = "test".

So now consider if you have SecondActivity and I am starting it from MainActivity using getInent();

Intent intent = getIntent();
intent.setClassName("com.example.pkg", "com.example.pkg.SecondActivity"");
intent.setComponent(new ComponentName("com.example.pkg", "com.example.pkg.SecondActivity"));
intent.putExtra("isLoggedIn",true);
startActivity(intent);

Then in my SecondActivity I can access key and isLoggedIn both.

Intent intent = getIntent();
String value = intent.getString("key"); // value will = "test".
boolean testIsLoggedIn = intent.getBooleanExtra("isLoggedIn",true);

So, generally it is not good practice to use the getIntent to start further activities.

Upvotes: 8

Related Questions