Android. How to start activity without creating new one? - java

I tried to set attribute android:launchMode="singleTask" for calling Activity, but it still does not works as I expected.
I need that method onCreate(Bundle bundle) to be called only once, but it still calls each time when I start Activity.
I start Activity using code like this:
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), NextActivity.class);
startActivity(myIntent);
}
Please let me know what I am doing wrong

It must be like this:
android:launchMode="singleTop"
and calling:
Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Already existed topic about this: Android: new Intent() starts new instance with android:launchMode="singleTop"

Even if you make your launch mode 'singleTop', a new activity will be started.
At each activity creation, its onCreate() will be started.
My understanding is that the singleTop option, basically finishes the caller Activity.
I think that you may think that onCreate() is a form of Application constructor but it really is an Activity constructor. You may want to do your one time initializations elsewhere.

Related

Going back to previous activity [duplicate]

This question already has answers here:
Android: Go back to previous activity
(24 answers)
Closed 3 years ago.
I have two activities, How is it possible to go back to a previous activity.
What code do I need to go back to previous activity
Assuming you started the new activity with
startActivity(new Intent(this, SecondActivity.class));
puts the SecondActivity in front and the FirstActivity in the backstack. To go back to the FirstActivity, put this in your second activity.
finish();
If you start the activity with result like below :
From 1st Activity :
startActivityForResult(new Intent(this, SecondActivity.class),requestCode);
You can finish the activity with required intents :
From 2nd Activity :
// Optional if you want to pass values from second activity to first
Intent data = new Intent();
data.putExtra("key","any_value");
setResult(RESULT_OK,data);
// Just finish
finish();
Refer the below link for more information like onActivityResult callback and more
https://developer.android.com/training/basics/intents/result
1st Method
If you are using Intent then make sure you don't call finish(); method after using the following code,
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
By this code, the Back Button you created will do its work and go to previous Activity.
And also don't override the onBackPressed() method in Activity.
2nd Method
There is another way that you can achieve this by setting Home Button to go to specific Activity, For that, you have to create Back Button in Action Bar in onCreate() method.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
And in the AndroidManifest.xml file, you have to add the following,
<activity
android:name="com.example.yourapplication.SecondActivity"
android:label="#string/title_second_activity"
android:parentActivityName="com.example.yourapplication.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourapplication.MainActivity" />
</activity>
using intent
intent = new Intent(this, SecondActivity.class);
startActivity(intent);
Or you can use onBackPressed() if the activity added to backstack
onBackPressed();

Does onCreate create an instance of the class? [duplicate]

For example
Intent intent = new Intent(this, SecondActivity.class);
eclipse error: The method setClass(Context, Class) in the type
Intent is not applicable for the arguments (FirstActivity.ClickEvent,
Class)
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
But that will be correct.
Anybody can explain the difference between those two ?
Thanks.
this refers to your current object. In your case you must have implemented the intent in an inner class ClickEvent, and thats what it points to.
Activity.this points to the instance of the Activity you are currently in.
Shubhayu's answer is correct, but I just want to make clear for anyone who see this question that this and Activity.this is the same if you are using it directly in the activity.
This is answered here
Example:
#Override
protected void onResume() {
super.onResume();
Log.d("Test", this.toString());
Log.d("Test", MainActivity.this.toString());
}
Result:
D/Test: com.example.app.MainActivity#e923587
D/Test: com.example.app.MainActivity#e923587
When you are pointing to this inside click event, it is pointing to the click listener.
You are intent to transfer control from one activity to another and for that u ll have to specify an event basically and hence the error.
this means the entire activity and firstactivity.this means an event occurring for example a a button clicked.........

Android Is An Intent Unique To An Activity or Global

I'm curious as to whether an intent is unique to a set activity or not.
For example, my current usage of an intent is to give it some data from Activity 1 and pass it on to Activity 2.
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("id", id.getText().toString());
intent.putExtra("weight", weight.getText().toString());
intent.putExtra("zipTo", zipTo.getText().toString());
intent.putExtra("locationId", locationID.getSelectedItem().toString());
intent.putExtra("imageNum", 1);
startActivity(intent);
Now, in MainActivity I can use the following code to retrieve the data passed from the previous activity.
Bundle bundle = getIntent().getExtras();
id = bundle.getString("id");
weight = bundle.getString("weight");
locationID = bundle.getString("locationID");
zipTo = bundle.getString("zipTo");
After doing some work in MainActivity, I need to return to the previous activity that sent us to MainActivity (and I need the data that was originally sent to return).
Do I need to redefine an intent, and do "intent.putExtra" for each value again in MainActivity before sending it to the first Activity? Or is the intent global, and once defined in one activity I can use it in the others with getIntent().getExtras()?
Intents are not global. You only have access to the bundle in the activity you started with the intent passed.
You should use startActivityForResult(intent). This provides the behavior youre looking for.
Getting a result from an activity
The idea is you start the new intent. In this case 'MainActivity'. Once you are done with your logic in MainActivity you use the strategy above to pass a result back to the activity that started MainActivity.
information passed through intents are not global from one activity to another, what is global is shared preferences and information that is metadata which is stored in manifest.xml.

intent flag over intent startActivity(i);

#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(getApplicationContext(), Profile.class);
startActivity(i);
}
});
what is the difference of using this code and what difference does it do on the program compared to this doe
Intent i = new Intent(CurrentActivityName.this, NextActivityName.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
First one uses getApplicationContext() to launch the intent.
Application context is attached to the application's life-cycle and will always be same throughout the life of application. So if you are using Toast, you can use application context or even activity context (both) because a toast can be raised from anywhere with in your application and is not attached to a window.
Second one uses the Activity context.
Activity context is attached to the Activity's life-cycle and can be destroyed if the activity's onDestroy is raised. If you want to launch a new activity, you must need to use activity's context in its Intent so that the new launching activity is connected to the current activity (in terms of activity stack).
So, Whenever you need to manipulate Views then go for Activity-Context, else Application-Context would be enough.
Source: this answer at difference and when to use getApplication(), getApplicationContext(), getBaseContext() and someClass.this question.
Also, reading some of above links would help:
What's the difference between the various methods to get a Context?
getApplicationContext(), getBaseContext(), getApplication(), getParent()

Android activity stack control. Can't figure out how to remove history

I have following 2 activities(plus many more not important for this question):
<activity android:name=".activities.HomeActivity" android:excludeFromRecents="true" />
<activity android:name=".activities.AdHocActivity" android:noHistory="true"/>
HomeActivity is a first one and only one wich I keep history for. User can go differnt places from Home and click Back to come back to main HomeActivity.
I also have service running on alarm and checking for some specific things. When specific criteria met I'm displaying my AdHocActivity
Intent i = new Intent(context, AdHocActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(BlockingActivity.INTENT_BLOCKED_PACKAGE_NAME, packageName);
context.startActivity(i);
FLAG_ACTIVITY_NEW_TASK was necessary to show Activity from BroadcastReceiver
Now, this AdHoc activity displays some message to user and has a button to take user back to HomeActivity
private void sendToMainApplication()
{
Intent i = new Intent(this, HomeActivity.class);
startActivity(i);
finish();
}
All this work, but I get second instance of HomeActivity in a stack. So now when user taps "Back" - my Home activity flashes and comes back (previous copy).
I want only one copy to stay on top. I want it to be like anchor one. If it doesn't exist - I want new one to be opened.
The trick to prevent HomeActivity from being doubled was to call it like this:
private void sendToMainApplication()
{
Intent i = new Intent(this, HomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}

Categories