Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent duplicate activities

Tags:

java

android

So, I'm both new to Java and to creating android apps, but not new to programming. I've read through most of the developer.android.com site, but I haven't been able to find this:

I want to make sure that a certain activity isn't running more than once at the same time. So we have a task somewhat like this:
Activity A) a TabActivity, which launches
Activity B) a ListView that, on-click, opens up
Activity C) which is the interface for a mediaplayer object

Right now, whenever somebody presses the back-button whilst in C (Which is a likely thing, because they're going to listen to a streaming 1-hour long mp3) and then presses another list item, instead of returning to C, C is opened a second time, and two streams are playing. Of course, I'd want only one instance of C running, and I want a second click on the list item to bring C back to the front. This could also be useful for notification intents.

I've been messing around with the flags (especially FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_REORDER_TO_FRONT), but no success so far.

If someone could help me out here I could focus on my next challenge - making it a real feed reader :P

Thanks in advance,

like image 788
Vic V Avatar asked Oct 22 '10 22:10

Vic V


People also ask

How do you prevent work duplication?

Communication is the first step in preventing duplication of work. Duplication of work happens due to the lack of communication among cross-functional teams. In our previous example, if there was a proper line of communication between marketing and product teams, they could have collaborated and researched together.

What is duplication of work?

uncountable noun. If you say that there has been duplication of something, you mean that someone has done a task unnecessarily because it has already been done before. [...]


2 Answers

You need to flag your actvity as either "singleTask" or "singleInstance" in your manifest. I can't remember the exact differences between the 2, but either should do what you want. SingleInstance just does something different with the stack.

Example :

<activity android:name="MainActivity" android:launchMode="singleInstance"></activity>

You can handle new calls to startActivity() from the same activity instance with onNewIntent()

like image 78
Falmarri Avatar answered Oct 09 '22 19:10

Falmarri


I've got it!

For those reading this question and wanting to know the summary: I mistakenly thought more then one activity was running, but it appeared more MediaPlayer instances where running. I made my mediaplayer a class member and am now controlling it from the onStart() event.

I am using SharedPreferences to check if the stream needs to reset and change source, or continue running and just show the interface.

Thanks for all your reactions. Really helped me out.

like image 35
Vic V Avatar answered Oct 09 '22 18:10

Vic V