简体   繁体   English

应用程序销毁后在应用程序中打开相同的活动

[英]Opening the same activity in application after the app is destroyed

I want to open the same activity which the user was using before the app was quit or destroyed. 我想打开用户在退出或销毁应用程序之前正在使用的相同活动。 How Can I do that? 我怎样才能做到这一点? Please help.... 请帮忙....

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). 当通过主屏幕上的图标启动时,Android始终会使用AndroidManifest.xml中的android.intent.action.MAIN过滤器启动该活动,除非该应用程序已经在运行(在这种情况下,它将显然将活动还原到堆栈)。

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. 要实现您所描述的内容,您可以简单地将最后一个可见活动存储在SharedPreferences中,并具有一个Dispatcher活动,该活动根据首选项启动最后一个活动。

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: 和一个Dispatcher活动类似以下内容:

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 您可以为onPause覆盖创建基类
  • The Dispatcher activity obviously needs to be the android.intent.action.MAIN action Dispatcher活动显然需要是android.intent.action.MAIN操作

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

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