How to find back stack activities in an android application?

百般思念 提交于 2019-11-30 01:03:14

The code below can be used to extract all the tasks and the top activity within each task in the back stack

ActivityManager m = (ActivityManager) ctx.getSystemService( ctx.ACTIVITY_SERVICE );
List<RunningTaskInfo> runningTaskInfoList =  m.getRunningTasks(10);
Iterator<RunningTaskInfo> itr = runningTaskInfoList.iterator();
while(itr.hasNext()){
    RunningTaskInfo runningTaskInfo = (RunningTaskInfo)itr.next();
    int id = runningTaskInfo.id;
    CharSequence desc= runningTaskInfo.description;
    int numOfActivities = runningTaskInfo.numActivities;
    String topActivity = runningTaskInfo.topActivity.getShortClassName();
}

You can use "adb shell dumpsys activity activities" command

for reference http://www.onsandroid.com/2015/01/find-back-stack-activities-in-android.html

android developer

I think you can do it by listening to the changes of the activities, via this API of registerActivityLifecycleCallbacks :

https://developer.android.com/reference/android/app/Application.html#registerActivityLifecycleCallbacks(android.app.Application.ActivityLifecycleCallbacks)

https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html

This will help you to add to a stack of your own classes, and see the full state as you wish.

I'm not sure i get it well...You want to go back to the previous activity ? If so, finish the current activity you'll get back to the previous one.

actually, you can get the task id from the runningtaskinfo using getRunningTasks and then, get the recenttaskinfo using getRecentTasks by compare the task id. now you can restart that activity using startactivity, with the baseintent in the recenttaskinfo.

As getRunningTasks(..) has been deprecated or if you don't want to add special permissions to your app here is an alternative solution if all activities are yours: you can mark an identifier (not the activity itself is it may be in need to be garbage collected) in a singleton Stack, LinkedList or LinkedHashSet: in onPause() add the identifier to the stack and remove it in onResume().

You can check the contents of that stacks to know if there is any activity and the sequence they have been created.

You can clean up your code and forget to do that manually if all your activities derive from a common base activity for your app.

I recommend you to utilize startActivityForResult instead of startActivity, then in order to retrieve the origin/source activity- call getCallingActivity().getClassName().

How will A know it came from home? Use getIntent() its getAction() -> android.intent.action.MAIN and getCategories() -> android.intent.category.LAUNCHER

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!