clearing stack of activities with just one press

2019-06-11 08:50发布

I have a launching Activity A1 which has a start button which starts a Service S1:

startButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Log.i(TAG1, "Starting Update Service");
                startService(serviceIntentS1);
            }
        });

S1 depending on some condition starts Activity A2:

if (giveninteger>=2)
       {   
           Intent intentA2= new Intent(this, A2.class);
           // following line to avoid exception
           intentA2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //to avoid exception
           startActivity(intentA2);  

         }

A2 subscribes to S1 and from A2 user can see periodically updated data by the aid of S1. A2 has following code to stop S1 service:

public void onBackPressed() {
        try {
            Log.i(TAG2, "Killing Update Service");
            stopService(serviceIntentS1);

              } catch (NullPointerException e) {
            Log.i(TAG3, "Service was not running " + e.toString());
        }
        finish();
        System.exit(0);
        return;
    }  

My problem is that, if the update runs 10 times from A2, user has to press back button 10 times to exit Activity A2. That is instances of A2 are accumulated in Activity stack. I tried all flags during launch of A2 from S1, but without success. I want to exit the Activity A2 with just one back press, no matter how many times the update runs.

Any suggestions would help.

1条回答
贪生不怕死
2楼-- · 2019-06-11 09:12

What you need is a SingleInstance of A2 so that irrespective of the number times A2 is launched only one instance remains and you need to press back button only once. Define this attribute in the AndroidManifest file.

<activity android:launchMode"singleInstance"/>
查看更多
登录 后发表回答