Can you tell me how to run my second activity
if my first activity
is closed?There can be some time before the second activity must be opened.Should I use a Service
?And please give an example.Thank you so much.

- 1
- 4
-
In what case are you wanting to run the second activity? – Knossos Jan 13 '16 at 16:33
-
I want that first activity was closed for some time and then the second one can be opened – Konar Jan 13 '16 at 16:56
3 Answers
The answer will depend under what condition you want to start the next activity. Following is just a sample, whatever is done in the onDestroy can be copied anywhere else to start the next activity.
Override the onDestroy method of the first activity and then fire an intent to start the second activity. In your first activity,
public class A extends Activity{
.
.
.
@Override
public void onDestroy(){
Intent in = new Intent(this, SecondActivity.class);
startActivity(in);
.
.
.
}
}
Make sure both the Activities are metioned in the AndroidManifest.xml
EDIT: To start after some time, you can use a Handler like this. (NOTE : This one is not tested. I hope it works as expected)
public void onDestroy(){
new Handler.postDelayed(new Runnable(){
public void run() {
Intent in = new Intent(this, SecondActivity.class);
startActivity(in);
}
}, 7000);
}
7000 over here is the milliseconds after which you want to start the next activity. i.e the next activity will start after 7s.
All the best :)

- 1,459
- 1
- 18
- 33
-
Thank you for your answer! But I forgot to mention one thing: second activity can be opened after some time the first one was closed. – Konar Jan 13 '16 at 16:54
if my first activity is closed
For me it sounds like you mean "closed as a result of a user action". Starting a new Activity
from onDestroy()
is a bad idea since the system may destroy your Activity
if it needs to. It can also be destroyed if the device is rotated. A better approach is overriding the back button:
@Override
public void onBackPressed() {
//delay 2nd Activity launch
super.onBackPressed();
}

- 11,485
- 17
- 93
- 141
If you try to delay a launch of a second Activity from within your first Activity, you risk it not opening at all, if the app is cleared from memory. Your best bet is to use AlarmManager
to schedule the opening of a new Activity after a certain amount of time. This puts the work on the Android OS instead of in your app.
This post contains some code examples of how to approach this.
-
But how I understand AlarmManager can only open Broadcast Receivers,can't it?(Because of the pending intent). – Konar Jan 13 '16 at 17:14
-
@Konar I am not positive of the limitations, however if that is the case, you can simply launch the Activity from the Broadcast Receiver (which I believe requires a custom launch Flag). Something like [this](http://stackoverflow.com/a/16666632/763080) should do the trick. – Phil Jan 13 '16 at 17:38