android - 返回 Activity 而不创建新实例

标签 android android-intent android-activity

我有一个 SplashScreenActivity,如果 MainActivity 上没有检测到触摸,它将每 2 分钟运行一次。如果按下 SplashScreenActivity 上的“开始”按钮,则会启动 MainActivity。

我的问题是,当在 SplashScreenActivity 上按下“开始”按钮时,每次都会创建一个新的 MainActivity 实例,从而每次都会加载我的库并进行初始化(在 OnCreate() 中)。这显着减慢了我的应用程序的速度,并且在按下按钮时出现滞后。我只希望在应用程序首次启动时运行一次

我尝试过使用

    new Handler().postDelayed(new Runnable() {       
            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);   
                startActivity(i);

                // close this activity
                finish();
            }
    }, SPLASH_TIME_OUT);        

...当 Intent 启动时,但我的库和 MainActivity 中 OnCreate() 中的初始化仍在再次运行。

当在 SplashScreenActivity 中按下“开始”按钮时,运行以下方法:

    public void startIntent(View v){
         Intent i = new Intent(SplashScreen.this, MainActivity.class);
         i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);   
         startActivity(i);
     }

有什么帮助吗?


当前有以下行(取出 setFlags):

Intent intent = new Intent(Email.this, MainActivity.class);
startActivity(intent);

每次 Activity 启动时,仍然会调用 MainActivity 的 OnCreate()。


所以我发现如果我设置以下内容:

intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  

我可以成功返回到我的 MainActivity,而无需创建新实例。

点击here了解更多信息。

最佳答案

如果您只想显示SplashScreen(即图片), 那么你应该考虑在任何布局中创建一个与主布局处于同一级别的ImageView

然后您可以在代码中使ImageView/SplashScreen 可见或不可见

这样您可以节省大量工作。

关于android - 返回 Activity 而不创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18068842/

相关文章:

android - 如何从android流式传输到ffserver

java - 创建登录类型的 Activity 并强制它成为唯一的开放点

java - 跨所有 Activity 的 API 类

java - 带有 ProgressDialog 的外部 AsyncTask 类 [更新 : and returning back?]

android - Activity.setResult(int) 和 Activity 生命周期

android - 使用 ContentProvider 进行复杂原始查询的优雅方式

android - 将 Intent 从广播接收器发送到android中正在运行的服务

java - Android StartActivity() 崩溃

java - 奥利奥,默认短信应用程序和 ACTION_RESPOND_VIA_MESSAGE

java - Android:重新打开 Activity 的应用程序中出现 OutOfMemory 异常