简体   繁体   English

一键清除活动堆栈

[英]clearing stack of activities with just one press

I have a launching Activity A1 which has a start button which starts a Service S1: 我有一个启动Activity A1,它具有一个启动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: S1根据某些条件启动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订阅了S1,并且来自A2的用户可以借助S1定期查看更新的数据。 A2 has following code to stop S1 service: A2具有以下代码来停止S1服务:

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. 我的问题是,如果更新从A2运行10次,则用户必须按10次返回按钮才能退出Activity A2。 That is instances of A2 are accumulated in Activity stack. 也就是说,A2的实例累积在“ Activity堆栈中。 I tried all flags during launch of A2 from S1, but without success. 我在从S1启动A2的过程中尝试了所有标志,但没有成功。 I want to exit the Activity A2 with just one back press, no matter how many times the update runs. 无论更新运行了多少次,我都想一按就退出Activity A2。

Any suggestions would help. 任何建议都会有所帮助。

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. 您需要的是A2的SingleInstance,因此无论启动A2的次数是多少,都只剩下一个实例,并且只需要按一次Back按钮即可。 Define this attribute in the AndroidManifest file. 在AndroidManifest文件中定义此属性。

<activity android:launchMode"singleInstance"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM