Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid multiple instances of same Activity?


In my PoC, I have some Activities, HomeActivity, CreateActivity, SearchActivity, ResultsActivity, ResultDetailsActivity, and UpdateActivity.

I have two main navigation paths: Create and Search.

Navigation for the Create path is as follows: HomeActivity--> CreateActivity -(on complete)-> HomeActivity

Navigation for Search is as follows: HomeActivity--> SearchActivity --> ResultsActivity(ListActivity) --> ResultDetailsActivity --> UpdateActivity -(on complete)-> ResultDetailsActivity (with updated data).

Currently, navigation to a new Activity is via startActivity(intent) method. However, this is causing multiple instances of each Activity to be opened.

I'm rather new to Android. Could someone please suggest how I could avoid this?

like image 718
Debojit Avatar asked May 16 '12 08:05

Debojit


People also ask

What is an activity stack?

A task is a collection of activities that users interact with when trying to do something in your app. These activities are arranged in a stack—the back stack—in the order in which each activity is opened. For example, an email app might have one activity to show a list of new messages.

What is taskAffinity?

Task affinity lets you define which task an activity belongs to. By default, an activity has the same task affinity as its root activity. With task affinity, we can now separate activities into different tasks.

What is intent flag_ activity_ new_ task?

FLAG_ACTIVITY_NEW_TASK is equivalent to launchMode=singleTask and in there I read. However, if an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance.

Can I run two instances of Android studio?

Go to: File -> Settings -> Appearance & Behavior -> System Settings -> Project Opening. Check [x] "Confirm window to open project in". Now open the other (2nd) project with File -> Open... etc. You will now be asked if you want to open a new window or replace what you already have.


1 Answers

In your android manifest, Add to your <activity> tag the android:launchMode="singleTask"

For a full list, check the documentation of activity

In your manifest:

    <activity android:name=".YourActivity"               android:launchMode="singleTask"               android:label="@string/app_name" /> 

Note: don't use singleton.

like image 84
Sherif elKhatib Avatar answered Sep 21 '22 17:09

Sherif elKhatib