Could please someone give me an example of how we can create a task back stack with having an Activity, which has launchMode=singleTask, at top of the stack and it's not the only activity in the back stack.
For example, we have one such task in the below diagram (the one including Activity X & Y);
As far as I know, singleTask activity is supposed to be the root one and task elements can never be rearranged.
Thanks in advance
Create an app Application1 with four Activities:
Activity1
Make sure that it is not exported="false" (that is, it's true either explicitly or implicitly)
Make it the launcher
Activity2
ActivityX
ActivityY
It's the one: launchMode="singleTask"
In Activity1 implement two actions, e.g. two distinct buttons each doing the following:
Start Activity2 and finish itself
Start Activity2 and do not finish itself
In Activity2 implement two actions:
Start ActivityX and finish itself
Start ActivityY and do not finish itself
In ActivityX implement one action:
Start ActivityY and do not finish itself
ActivityY do nothing :)
Create another app Application2 with an Activity:
AnotherActivity
Make it the launcher
In AnotherActivity implement one action:
Start Activity1. You can do it like this:
Intent intent = new Intent();
// package, fully qualified class name
intent.setComponent(new ComponentName(
"com.stackoverflow", "com.stackoverflow.Activity1");
startActivity(intent);
Launch Application1, which will start Activity1
In Activity1, start Activity2 finishing itself
In Activity2, start ActivityX finishing itself
In ActivityX, start ActivityY
Press home
Launch Application2, which will start AnotherActivity
In AnotherActivity, start Activity1
In Activity1, start Activity2 without finishing itself
In Activity2, start ActivityY without finishing itself
There you go. Pop the stack with the back button now.
Actually, this is pretty easy to do.
To generate a task that contains X at the root and Y on top, even though Y is declared with launchMode="singleTask":
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity android:name=".X">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".Y" android:launchMode="singleTask"/>
</application>
In activity X just launch activity Y like this:
startActivity(new Intent(this, SingleTaskActivity.class));
You will now have a task with activity X at the root and activity Y on top of that.
This happens even if you explicitly say that you want Y launched in a new task, like this:
Intent intent = new Intent(this, SingleTaskActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
This seems counter-intuitive, but the reason is because both X and Y have the same taskAffinity. And taskAffinity trumps launchMode when Android needs to decide how to launch an Activity.
taskAffinity, if not specifically set, defaults to the package name of the application. All activities with the same taskAffinity will be launched into the same task.
This confuses most developers, because the documentation doesn't mention taskAffinity very often.
If you really want to be sure that an Activity will always be the root of its task, no matter how it is launched, you need to use either launchMode="singleTask" or launchMode="singleInstance" and specify taskAffinity="" to indicate that the Activity has no task affinity (ie: it doesn't belong with any other activities).
Related
After looking into the codes i need to maintain/modify and the different documents and explanation, i really got confused single task and task affinity.
https://developer.android.com/guide/topics/manifest/activity-element.html
https://www.slideshare.net/RanNachmany/manipulating-android-tasks-and-back-stack
https://developer.android.com/guide/components/activities/tasks-and-back-stack.html
What i understand is activity launch mode singleTask will create a new task and put that activity at the root of the task. "singleTask" and "singleInstance", should be used only when the activity has an ACTION_MAIN and a CATEGORY_LAUNCHER filter
activity taskAffinity is the task that the activity has an affinity for. By default all the activities share the same affinity, the default package name. If want to have the activity different affinity task, then define another name and launch with FLAG_NEW_ACTIVITY_TASK.
In my maintain code(not the original developer), there have so many activities in AndroidManifest.xml with launchMode singleTask.
<activity name="LauncherActivity"
launchMode="singleTask">
<intent-filter>
<action name="action.MAIN" />
<category name="category.LAUNCHER />
</intent-filter>
</activity>
<activity name="TabsActivity"
launchMode="singleTask">
</activity>
<activity name="SubTab1"
launchMode="singleTask">
</activity>
<activity name="SubTab2"
launchMode="singleTask">
</activity>
<activity name="SubTab3"
launchMode="singleTask">
</activity>
<activity name="SubTab4"
launchMode="singleTask">
</activity>
<activity name="ScreenActivity"
launchMode="singleTask"
taskAffinity="com.xxx.xxx.sa"
excludeFromRecents="true">
</activity>
When click on user icon,
it will launch the LauncherActivity. LauncherActivity do some tasks for checking and launch TabsActivity and finish
itself(LauncherActivity).
TabsActivity add Tabs (SubTab1, SubTab2, SubTab3, SubTab4).
ScreenActivity will be launched startActivity with
FLAG_ACTIVITY_NEW_TASK.
ScreenActivity also put a notification icon so that the user can directly back to this activity.
SubTab can launch the other standard launchMode which will be destroyed after use back key.
EveryTime user click on App icon, it will take to TabsActivity instead of the last activity the user interact. So I add some code in the LauncherActivity onCreate()
if (!isTaskRoot() && !TextUtils.isEmpty(action)) {
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) &&
Intent.ACTION_MAIN.equals(action)) {
finish();
return;
}
}
This successfully bring to the last activity that the user interact.
The first question comes to me that isTaskRoot(). According to the explanation:
boolean isTaskRoot ()
Return whether this activity is the root of a task. The root is the first activity in a task.
LauncherActivity defined as singleTask as mentioned above, so it should be the root in the task. But when onCreate() check that, it is not the root task when there is other activity is launched including SingleTask activity. When TabsActivity is launched, when click on AppIcon, LauncherActivity onCreate() isTaskRoot() return false.
LauncherActivity and TabsActivity, they should be in different tasks and in each task, each would be the root activity.
In some other comments, it mentioned that isTaskRoot() is true when there are no activities in activity stack. So if there is activity in the stack, if will return false. So it is more related to the stack instead of task? I really get confused. Can someone explain about why it is different with document explanation.
The second modification is that I removed the ScreenActivity taskAffinity. In the old design, ScreenActivity can be be backed to through clicking on notification. But there is new request that if there is ScreenActivity last launched by user, when click on App icon, it should back to that activity. After removed taskAffinity in AndroidManifest, it does happen what i want.
I am looking this slide share tutorial. But still not get that.
https://www.slideshare.net/rajdeep/managing-activity-backstack
My question is that if the singleTask without taskAffinity, how they create a new task for each different singleTask activity. How the backstack works?
After modification, LauncherActivity, TabsActivity, ScreenActivity are SingleTask with the same default package name task. So they are in the same task stacked? If yes, it is not the same with document explanation. Please help me to get more clear of that.
Thanks a lot.
I have a problem with an activity which is started with FLAG_ACTIVITY_REORDER_TO_FRONT is not recreated and present on the screen after FLAG_ACTIVITY_CLEAR_TASK.
So the step is:
Open app, enter Welcome Activity.
Finish Welcome activity and start activity A without specific intent flag.
Start activity B with FLAG_ACTIVITY_REORDER_TO_FRONT from activity A (new instance of B is created and now stack became A->B).
Start activity A from B with FLAG_ACTIVITY_REORDER_TO_FRONT (existing A instance brought to top of stack so stack became B->A).
And under some condition, I need to start over from the beginning (just like another normal app launch), so started Welcome activity using FLAG_ACTIVITY_CLEAR_TASK.
So the app will enter phase 2 again after phase 1, which is what I expected, but then, if I try to start activity B again with FLAG_ACTIVITY_REORDER_TO_FRONT from activity A, there is activity B's callback 'onNewIntent, onStart, onResume' in a row, but it doesn't present on the screen.
It looks like to me that there is still the previous instance of activity B somewhere but not showing to me.
I don't specify launch mode for either activity A or B.
I know that document says about FLAG_ACTIVITY_CLEAR_TASK that "This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.". And use them together does solve my problem, but then if I click home button to put app background and then launch again, it will become another app launch (enter phase 1) but not back to the previous top activity.
So my questions are:
When I use FLAG_ACTIVITY_CLEAR_TASK to start welcome activity, I don't see onDestroy of either activity A or B, is it by design?
If they are not destroyed, where do they stay and can I have a reference to them?
How can I make activity B presented on the screen after all of these steps?
Code for phase 5:
Intent i = new Intent(A.this, WelcomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Thanks in advance.
AndroidManifest.xml
<activity
android:name=".activity.WelcomeActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activity.A_Activity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:theme="#style/BaiduMapTheme.MainMap"
android:windowSoftInputMode="adjustPan" />
<activity
android:name=".activity.B_Activity"
android:configChanges="locale|fontScale|keyboard|keyboardHidden|layoutDirection|mcc|mnc|navigation|orientation|screenLayout|screenSize|touchscreen|uiMode"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
OK, now I think I have those questions because of my incorrect using of the intent flags.
First of all, I should use FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK at the same time as the document says.
Then everything looks normal and as expected, except one that: if I put the app into background and then click the launch icon again, the WelcomeActivity will be created again.
Previously I thought my existing activity stack is cleared and a new WelcomeActivity is created, but it turns out the existing activity stack is still there, but an extra WelcomeActivity is created, so what I need to do is add some extra flag in WelcomeActivity to determine if it's created in this condition, if yes, then just call finish() in onCreate(), then I can back to the previous activity I was in before enter background.
I have an Activity_1 after a lot of steps, say
Activity_2 > Activity_3 .... in some Activity_n I change some data related to Activity_1 and call it using
Intent intent = new Intent(Activity_n.this, Activity_1.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
To refresh the content. But later I can go all the way back to Activity_1 where I started, which has old data.
Instead I want the initial Activity_1' s onResume() to be called, using the above code. Or appropriate Flag
FLAG_ACTIVITY_CLEAR_TOP
consider a task consisting of the activities: A, B, C, D. If D calls
startActivity() with an Intent that resolves to the component of
activity B, then C and D will be finished and B receive the given
Intent, resulting in the stack now being: A, B.
That' what the docs say, but not what I am getting.
You can add this two lines and try
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Write this in your manifest file inside Activity
<activity
android:name=".SettingsActivity"
android:launchMode="singleInstance"
android:screenOrientation="portrait" >
</activity>
"singleTask" and "singleInstance" activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task.
You can use SingleTask or SingleInstance
"singleTask" - The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.
"singleInstance" - Same as "singleTask", except that the system doesn't launch any other activities into the task holding the instance. The activity is always the single and only member of its task.
Refer this link http://developer.android.com/guide/topics/manifest/activity-element.html
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Visit : http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_REORDER_TO_FRONT
Resume Activity from backstack if exists or create a new one if not
android:launchMode="singleTask"
add this line to your app's AndroidManifest.xml and start the activity with a normal Intent.
I've set an alarm to start an activity, say A.
If the intended A activity is not in the foreground, A will wake up and hit onResume(), where I check to see the source of it.
But what if A is IN the foreground, what happens to my intent ?
Thanks !
It will depend how the launchmode is defined for activity A. For instance, if it's set to standard:
<activity android:name=".Activity" android:launchMode="Standard">
it will spawn a second activity when the intent is fired, and spawn as many activities as there are intents, where's if it's set to "singleTop":
<activity android:name=".Activity" android:launchMode="singleTop">
it will simply route the intent to the instance of the activity that's already running. There are two more types: "singleInstance" and "singleTask", so see the documentation for more details in order to customize as you wish.
My main activity A has as set android:launchMode="singleTask" in the manifest. Now, whenever I start another activity from there, e.g. B and press the HOME BUTTON on the phone to return to the home screen and then again go back to my app, either via pressing the app's button or pressing the HOME BUTTONlong to show my most recent apps it doesn't preserve my activity stack and returns straight to A instead of the expected activity B.
Here the two behaviors:
Expected: A > B > HOME > B
Actual: A > B > HOME > A (bad!)
Is there a setting I'm missing or is this a bug? If the latter, is there a workaround for this until the bug is fixed?
FYI: This question has already been discussed here. However, it doesn't seem that there is any real solution to this, yet.
This is not a bug. When an existing singleTask activity is launched, all other activities above it in the stack will be destroyed.
When you press HOME and launch the activity again, ActivityManger calls an intent
{act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER]flag=FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_RESET_IF_NEEDED cmp=A}
So the result is A > B > HOME > A.
It's different when A's launchMode is "Standard". The task which contains A will come to the foreground and keep the state the same as before.
You can create a "Standard" activity eg. C as the launcher and startActivity(A) in the onCreate method of C
OR
Just remove the launchMode="singleTask" and set FLAG_ACTIVITY_CLEAR_TOP|FLAG_ACTIVITY_SINGLE_TOP flag whenever call an intent to A
From http://developer.android.com/guide/topics/manifest/activity-element.html on singleTask
The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.
This means when the action.MAIN and category.LAUNCHER flags targets your application from the Launcher, the system would rather route the intent to the existing ActivityA as opposed to creating a new task and setting a new ActivityA as the root. It would rather tear down all activities above existing task ActivityA lives in, and invoke it's onNewIntent().
If you want to capture both the behavior of singleTop and singleTask, create a separate "delegate" activity named SingleTaskActivity with the singleTask launchMode which simply invokes the singleTop activity in its onCreate() and then finishes itself. The singleTop activity would still have the MAIN/LAUNCHER intent-filters to continue acting as the application's main Launcher activity, but when other activities desire calling this singleTop activity it must instead invoke the SingleTaskActivity as to preserve the singleTask behavior. The intent being passed to the singleTask activity should also be carried over to the singleTop Activity, so something like the following has worked for me since I wanted to have both singleTask and singleTop launch modes.
<activity android:name=".activities.SingleTaskActivity"
android:launchMode="singleTask"
android:noHistory="true"/>
public class SingleTaskActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
intent.setClass(this, SingleTop.class);
startActivity(intent);
}
}
And your singleTop activity would continue having its singleTop launch mode.
<activity
android:name=".activities.SingleTopActivity"
android:launchMode="singleTop"
android:noHistory="true"/>
Good luck.
Stefan, you ever find an answer to this? I put together a testcase for this and am seeing the same (perplexing) behavior...I'll paste the code below in case anyone comes along and sees something obvious:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example" >
<uses-sdk android:minSdkVersion="3"/>
<application android:icon="#drawable/icon" android:label="testSingleTask">
<activity android:name=".ActivityA"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".ActivityB"/>
</application>
</manifest>
ActivityA.java:
public class ActivityA extends Activity implements View.OnClickListener
{
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.main );
View button = findViewById( R.id.tacos );
button.setOnClickListener( this );
}
public void onClick( View view )
{
//Intent i = new Intent( this, ActivityB.class );
Intent i = new Intent();
i.setComponent( new ComponentName( this, ActivityB.class ) );
startActivity( i );
}
}
ActivityB.java:
public class ActivityB extends Activity
{
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.layout_b );
}
}
I tried changing minSdkVersion to no avail. This just seems to be a bug, at least according to the documentation, which states the following:
As noted above, there's never more than one instance of a "singleTask" or "singleInstance" activity, so that instance is expected to handle all new intents. A "singleInstance" activity is always at the top of the stack (since it is the only activity in the task), so it is always in position to handle the intent. However, a "singleTask" activity may or may not have other activities above it in the stack. If it does, it is not in position to handle the intent, and the intent is dropped. (Even though the intent is dropped, its arrival would have caused the task to come to the foreground, where it would remain.)
I think this is the behaviour you want:
singleTask resets the stack on home press for some retarded reason that I don't understand.
The solution is instead to not use singleTask and use standard or singleTop for launcher activity instead (I've only tried with singleTop to date though).
Because apps have an affinity for each other, launching an activity like this:
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if(launchIntent!=null) {
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
will cause your activty stack to reappear as it was, without it starting a new activity upon the old one (which was my main problem before). The flags are the important ones:
FLAG_ACTIVITY_NEW_TASK Added in API level 1
If set, this activity will become the start of a new task on this
history stack. A task (from the activity that started it to the next
task activity) defines an atomic group of activities that the user can
move to. Tasks can be moved to the foreground and background; all of
the activities inside of a particular task always remain in the same
order. See Tasks and Back Stack for more information about tasks.
This flag is generally used by activities that want to present a
"launcher" style behavior: they give the user a list of separate
things that can be done, which otherwise run completely independently
of the activity launching them.
When using this flag, if a task is already running for the activity
you are now starting, then a new activity will not be started;
instead, the current task will simply be brought to the front of the
screen with the state it was last in. See FLAG_ACTIVITY_MULTIPLE_TASK
for a flag to disable this behavior.
This flag can not be used when the caller is requesting a result from
the activity being launched.
And:
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED Added in API level 1
If set, and this activity is either being started in a new task or
bringing to the top an existing task, then it will be launched as the
front door of the task. This will result in the application of any
affinities needed to have that task in the proper state (either moving
activities to or from it), or simply resetting that task to its
initial state if needed.
Without them the launched activity will just be pushed ontop of the old stack or some other undesirable behaviour (in this case of course)
I believe the problem with not receiving the latest Intent can be solved like this (out of my head):
#Override
public void onActivityReenter (int resultCode, Intent data) {
onNewIntent(data);
}
Try it out!
I've found this issue happens only if the launcher activity's launch mode is set to singleTask or singleInstance.
So, I've created a new launcher activity whose launch mode is standard or singleTop. And made this launcher activity to call my old main activity whose launch mode is single task.
LauncherActivity (standard/no history) -> MainActivity (singleTask).
Set splash screen to launcher activity. And killed launcher activity right after I call the main activity.
public LauncherActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(intent);
finish();
}
}
<activity
android:name=".LauncherActivity"
android:noHistory="true"
android:theme="#style/Theme.LauncherScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Launcher screen theme should be set for the case that app is restarting after the process is killed. -->
<activity
android:name=".MainActivity"
android:launchMode="singleTask"
android:theme="#style/Theme.LauncherScreen"/>
Pros: Can keep the MainActivity's launch mode as singleTask to make sure there always is no more than one MainActivity.
If both A and B belong to the same Application, try removing
android:launchMode="singleTask"
from your Activities and test because I think the default behavior is what you described as expected.
Whenever you press the home button to go back to your home screen the activity stack kills some of the previously launched and running apps.
To verify this fact try to launch an app from the notification panel after going from A to B in your app and come back using the back button ..........you will find your app in the same state as you left it.
When using launch mode as singleTop make sure to call finish() (on current activity say A) when starting the next activity (using startActivity(Intent) method say B). This way the current activity gets destroyed.
A -> B -> Pause the app and click on launcher Icon, Starts A
In oncreate method of A, you need to have a check,
if(!TaskRoot()) {
finish();
return;
}
This way when launching app we are checking for root task and previously root task is B but not A. So this check destroys the activity A and takes us to activity B which is currently top of the stack.
Hope it works for you!.
This is how I finally solved this weird behavior. In AndroidManifest, this is what I added:
Application & Root activity
android:launchMode="singleTop"
android:alwaysRetainTaskState="true"
android:taskAffinity="<name of package>"
Child Activity
android:parentActivityName=".<name of parent activity>"
android:taskAffinity="<name of package>"
Add below in android manifest activity, it will add new task to top of the view destroying earlier tasks.
android:launchMode="singleTop" as below
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#style/AppTheme.NoActionBar">
</activity>
In child activity or in B activity
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), Parent.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
<activity android:name=".MainActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//Try to use launchMode="singleTop" in your main activity to maintain single instance of your application. Go to manifest and change.