Reputation: 1162
I have a boot receiver which receives BOOT_COMPLETED event and launches the default activity for my application as follows:
if(MyApplication.GetCurrentActivity()==null)
{
Intent mActivityIntent = new Intent(context, LauncherActivity.class);
mActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mActivityIntent);
}
I'm setting the activity after starting it. GetCurrentActivity() will return null if there are no activities launched or the last launched activity. So far there is no problem.
But if the user touches the app icon before the LauncherActivity has been launched, two instances of the same activities are created as they are in two different tasks (I guess). How to prevent this and launch only one instance of the activity.
Upvotes: 0
Views: 130
Reputation: 23344
Try -
if(MyApplication.GetCurrentActivity()==null)
{
Intent mActivityIntent = new Intent(context, LauncherActivity.class);
mActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
mActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(mActivityIntent);
finish();
}
UPDATE:
Then you can use FLAG_ACTIVITY_REORDER_TO_FRONT -
This flag will cause the launched activity to be brought to the front of its task's history stack if it is already running.-
if(MyApplication.GetCurrentActivity()==null)
{
Intent mActivityIntent = new Intent(context, LauncherActivity.class);
mActivityIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
startActivity(mActivityIntent);
finish();
}
For example -
Consider a task consisting of four activities:
A, B, C, D
. IfD
callsstartActivity()
with an Intent that resolves to the component of activity B, then B will be brought to the front of the history stack, with this resulting order:A, C, D, B
.
Upvotes: 1
Reputation: 2048
You can use:
<activity
android:name="name"
android:label="label"
android:launchMode="singleTop">
</activity>
This launch only one instance of the activity. Now, you can implement onNewIntent().
Hope it helps you :)
Upvotes: 0