Android - Show last viewed Activity When press (Home Button-->App Shortcut)

自闭症网瘾萝莉.ら 提交于 2019-12-24 02:38:17

问题


I came to do the eternal question, which so far have not found a solution, I searched on the internet the same problem but found a final solution to this problem.

when I have 2 activities open and I pull the 'Home Button' and then press the shortcut for my application, it shows me again the first activity (the launcher activity), and then to return to the activity that was displayed, I have to press the back button.

what is the solution to this problem?

I want to press the shortcut of my application (after having left my application by pressing the Home Button) show me the last activity was displayed, instead it shows me the first activity (activity launcher).

Thanks in advance.


回答1:


That is the expected behavior. The launcher will launch the Activity with the filter android.intent.action.MAIN.

There are ways to work around it, though. A very simple one is to have a boolean flag mRunning that you will set to true upon launch. If true, then on the onStart() method you start an intent to launch your second Activity; if false, then go on with setContentView().

If you have several activities to go back to, then a feasible approach is to save the current activity in SharedPreferences and launch it the same way.

Alternatively, your main Activity may be just an entry Activity whose only job is to start the last Activity used.

EDIT: I found this duplicate question: How to make an android app return to the last open activity when relaunched? that has a much better ansewr than mine.




回答2:


Your application is still running in the background when you press the home button. finish() the activity when you press the Home button if you want to go back.




回答3:


Depending on whether or not your main activity is ever launched by another activity, or only the application icon, you can use a much simpler solution. If your main activity is only launched by the application icon, you can use isTaskRoot() to check if your main activity is being launched as a fresh start to the application, or if the user is returning and the main activity is being laid on top of other activities that you wish to display instead.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (! isTaskRoot()) {
        finish();
    } else {
        ...
    }
}



回答4:


You can use startActivityForResult replace for startActivity when you want to open another Activity.



来源:https://stackoverflow.com/questions/6364418/android-show-last-viewed-activity-when-press-home-button-app-shortcut

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