How to start the activity that is last opened when launch an application?

我的未来我决定 提交于 2020-01-06 23:52:00

问题


I designed an app with several activities. There is only an activity instance in the back stack at any time. When I quit the application from an activity named AcitivityOne, how could I launch the application with ActivityOne next time?


回答1:


The fast method, is that in your onCreate() put those flags after setContentView():

if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
    finish(); 
    return; 
} 

Also you can create a SharedPreferences with the Activity last oppened as follows :

Modify your onPause() to this :

@Override
protected void onPause() {
  super.onPause();
  SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
  Editor editor = prefs.edit();
  editor.putString("lastopened", getClass().getName());
  editor.commit();
}

And then in your onCreate() again you put this :

Class<?> LastOpened;

    try {
        SharedPreferences prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
        LastOpened= Class.forName(prefs.getString("lastoppened", MainActivity.class.getName()));
    } catch(ClassNotFoundException ex) {
        LastOpened= MainActivity.class;
    }

    startActivity(new Intent(this, LastOpened));

If it doesn't help take a look at this thread



来源:https://stackoverflow.com/questions/36066476/how-to-start-the-activity-that-is-last-opened-when-launch-an-application

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