Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch main activity if activity stack is empty

I have one activity which can be launched from several other activites, along with url filter intents.

On this activity I use the home icon in the actionbar as a back button, bringing the user back to the previous activity (and not as a "home" action). For now I do this by calling the finish() function. This works fine when working from within the application.

However, if launching the activity by an url filter intent, I want the home icon to bring the user to the main activity. Obviously, calling finish() will just close the activity.

So my question is, is there a way to check whether my application stack is empty and then launch the main acivity if true? Or am I attacking this the wrong way?

like image 558
SveinT Avatar asked Jul 20 '12 10:07

SveinT


1 Answers

If your app is launched via url intent filter and it creates its own task, then you can use

if (isTaskRoot()) {
    // This activity is at root of task, so launch main activity
} else {
    // This activity isn't at root of task, so just finish()
}

EDIT: Added another possible method

If your app is launched into an existing task when it is launched via URL intent filter, then you can do something like the following:

When you launch your activity from other activities in your application, add an EXTRA to the Intent like this:

Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("internal", "true");
startActivity(intent);

When your activity gets launched it can then check for the presence or absence of the EXTRA in the Intent to determine whether it was launched internally or via URL intent-filter, like this:

Intent intent = getIntent();
if (intent.hasExtra("internal")) {
    // Launched internally
} else {
    // Launched via intent-filter
}
like image 101
David Wasser Avatar answered Oct 31 '22 03:10

David Wasser