0

I am making an application in which i want to make sure that only one instance of a single activity should remain in the stack.Please tell me how to achieve that.This is the coding which i was trying but have not got the intended result.

ArrayList<String> runningactivities = new ArrayList<String>();

    ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE); 

    List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE); 

        for (int i1 = 0; i1 < services.size(); i1++) { 
            runningactivities.add(0,services.get(i1).topActivity.toString());  
        } 

        if(runningactivities.contains("ComponentInfo{com.velosys.interview_preparation/com.velosys.interview_preparation.activities.MCQ}")==true){
             Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show(); 
            //MCQ.
        }

Thanks in advance

Naseeb Sheoran
  • 423
  • 2
  • 8
  • 21
  • Have you checked out a similar question like this? http://stackoverflow.com/questions/7075349/android-clear-activity-stack – gkiar Aug 23 '12 at 16:33
  • Also, doesn't `finish()` clear the activity from the stack? – gkiar Aug 23 '12 at 16:34
  • Sir actually i want to do like this. Activity A-> B ->C->A->B Only the latest instance of A should remain there and the previous instances should be removed. – Naseeb Sheoran Aug 23 '12 at 17:11

3 Answers3

1

That's a typical case for an Activity Launch Mode.

The official Android documentation is pretty precise and coherent imho.

Check out the paragraph android:launchMode. The singleTask mode might be what you are looking for.

jenzz
  • 7,239
  • 6
  • 49
  • 69
0

put inside the onStop() or the onPause() methods of the activity the "finish()" command. So every time you exit this activity it will be removed from the activity stack , so there will be no duplicate.

Panos
  • 7,227
  • 13
  • 60
  • 95
0

you can set intent flags while launching your activities. In your case FLAG_ACTIVITY_SINGLE_TOP and FLAG_ACTIVITY_CLEAR_TOP

sachy
  • 739
  • 7
  • 13
  • Sir actually i want to do like this. Activity A-> B ->C->A->B Only the latest instance of A should remain there and the previous instances should be removed. – Naseeb Sheoran Aug 23 '12 at 17:17
  • In this case while launch B you should call `finish()` for Activity A just after your startActivity() call for B, and so on – sachy Aug 23 '12 at 17:23