Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
64 views
in Technique[技术] by (71.8m points)

How to make an android app return to the last open activity when relaunched?

Is it possible to configure an android app so that if a user has opened your app, launched numerous activities, then returns to the home screen and relaunches your app again, instead of going to the main activity they will instead be taken to the activity highest on the stack (the most recent activity in your app)?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When launched via icon on the home screen, Android will always start the activity with the android.intent.action.MAIN filter in your AndroidManifest.xml, unless the application is already running (in which case it will obviously restore the activity on top of the stack).

To achieve what you described you can simply store the last visible activity in SharedPreferences and have a Dispatcher activity that starts the last activity according to the preferences.

So in every activity you want to re-start automatically:

@Override
protected void onPause() {
    super.onPause();

    SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putString("lastActivity", getClass().getName());
    editor.commit();
}

And a Dispatcher activity similar to the following:

public class Dispatcher extends Activity {

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

        Class<?> activityClass;

        try {
            SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
            activityClass = Class.forName(
                prefs.getString("lastActivity", Activity1.class.getName()));
        } catch(ClassNotFoundException ex) {
            activityClass = Activity1.class;
        }

        startActivity(new Intent(this, activityClass));
    }
}

Remarks

  • You could create a base class for the onPause override
  • The Dispatcher activity obviously needs to be the android.intent.action.MAIN action

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...