简体   繁体   English

当您有多个入口点活动时,清除活动堆栈吗?

[英]Clearing activity stack when you have multiple entry point activities?

I have an app which has multiple entry point activities. 我有一个具有多个入口点活动的应用程序。 I want to be able to clear my activity stack programmatically. 我希望能够以编程方式清除我的活动堆栈。 Imagine an app which requires user authentication, and the user wants to invalidate their session remotely (stolen device, for example). 想象一个需要用户身份验证的应用程序,而用户希望远程取消其会话(例如,被盗设备)。

In the case where an app has a single starting activity, we could just use: 如果一个应用只有一个启动活动,我们可以使用:

Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

to get back to the root activity. 回到根活动。 But my app may have been launched from different entry points, and so there might be different activity classes at the root of the stack. 但是我的应用程序可能是从不同的入口点启动的,因此堆栈的根部可能有不同的活动类。

Some options: 一些选项:

  1. Register a broadcast receiver in my base activity class which I can call from anywhere. 在我的基本活动课程中注册一个广播接收器,我可以从任何地方打电话。 In the handler, just call finish(), unwinding whatever stack may exist. 在处理程序中,只需调用finish()即可展开可能存在的堆栈。
  2. Use the frowned-upon System.exit(). 使用皱着眉头的System.exit()。
  3. In the above example, use Intent.FLAG_ACTIVITY_CLEAR_TASK in addition to the other two flags (but this is only available in api 11 and above...) 在上面的示例中,除了其他两个标志之外,还请使用Intent.FLAG_ACTIVITY_CLEAR_TASK(但这仅在api 11及更高版本中可用...)

Thanks 谢谢

You can check the name of activity at the root of the task stack and then start that activity with the FLAG_ACTIVITY_CLEAR_TOP. 您可以在任务堆栈的根部检查活动的名称,然后使用FLAG_ACTIVITY_CLEAR_TOP启动该活动。 If this root activity is not the activity you want then start the activity you want in onCreate and call finish(). 如果此根活动不是您想要的活动,则在onCreate中启动您想要的活动,然后调用finish()。
You can find the name of the root activity by 您可以通过以下方式找到根活动的名称

  1. call getTaskId () to get the task id. 调用getTaskId()获取任务ID。
  2. Obtain an ActivityManager object and call getRunningTasks to get a list of running tasks (check out the warning in the doc, I do not understand clearly) 获取一个ActivityManager对象并调用getRunningTasks来获取正在运行的任务的列表(查看文档中的警告,我不清楚)
  3. When the task in the list match the id above you can get the activity in the root using the field baseActivity 当列表中的任务与上面的ID匹配时,您可以使用baseActivity字段在根目录中获得活动

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

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