如何避免在启动 Activity 时调用 onCreate()? [英] How do I avoid onCreate() being called when starting an Activity?

查看:23
本文介绍了如何避免在启动 Activity 时调用 onCreate()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从堆栈中重新加载一个活动.

I want to reload an activity from stack.

我使用 startActivity() 来开始新的活动.当我在 Activity D 上时,我想重新加载 Activity A 而不是启动新的 Intent.从 D 调用 A 时我不能使用 startActivity() 因为它会触发启动的 onCreate()一个线程来获取一些数据.

I use startActivity() to start new activities. When I'm on Activity D I want to reload Activity A and not start a new Intent. I can't use startActivity() when calling A from D because it will fire onCreate() which starts a thread to fetch some data.

编辑:更新堆栈.

如果我使用 FLAG_ACTIVITY_REORDER_TO_FRONT 它会再次调用 onCreate() 方法.

If I use FLAG_ACTIVITY_REORDER_TO_FRONT it calls the onCreate() method again.

以下是我的场景.

Login Activity ̣→ Activity A → Activity B → Activity C → Activity D → Activity A

如何避免 onCreate() 被调用?

推荐答案

你必须采取完全不同的方法.使用 startActivity()startActivityForResult() 启动 Activity 并不重要,因为 onCreate(), onStart()onResume() 会在你启动一个 Activity 时被调用.

You have to take a totally different approach. It doesn't matter if you start your Activity with startActivity() or startActivityForResult() because onCreate(), onStart() and onResume() will be called when you start an Activity.

现在,如果您的 Activity 类中有一个方法可以启动另一个线程来完成某些工作,那么您必须使用标志.如果您的 Activity 需要在第一次执行时自动启动线程,那么您必须将其包裹在 if 子句中以检查您在第一次运行时设置的标志.

Now if you have a method in your Activity class that starts another thread to do some work then you have to work with flags. If your Activity requires to automatically start the thread on first execution then you have to wrap it around an if clause to check for a flag you set when it is first run.

这个想法是让你的 Activity 在线程第一次执行时在 Application 实例或 SharedPreferences 中将布尔值设置为 true.当您回到该 Activity 并且不希望该线程由于 onCreate() 被调用而自动运行时,您必须将调用代码包装在一些 if 子句中,如下例所示.

The idea is to have your Activity set a boolean to true in either your Application instance or SharedPreferences when the thread is first executed. When you come back to that Activity and don't want that thread to be run automatically due to onCreate() being called then you have to wrap your calling code around some if clause like in the example below.

这是一个例子.

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    // Other stuff

    if (!YourApplicationInstance.wasCalled) {
        // Run your thread or do something else you want to do only once.

        // Set the wasCalled flag to true to not run this code again
        // if onCreate() is called a second time.
        YourApplicationInstance.wasCalled = true;
    }
}

您必须阅读 在任何地方使用应用程序上下文? 以了解如何实现我的伪类 YourApplicationInstance.

You'll have to read Using Application context everywhere? to understand how to implement my pseudo class YourApplicationInstance.

这篇关于如何避免在启动 Activity 时调用 onCreate()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆