如何避免的onCreate()被调用开始的活动是什么时候? [英] How do I avoid onCreate() being called when starting an Activity?

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

问题描述

我要重新加载从堆栈中的活动。

I want to reload an activity from stack.

我用 startActivity()来开始新的活动。当我在活动ð的我想重装的活动A 的,而不是开始一个新的意图。我不能使用 startActivity()时调用的 A 的距离的ð的,因为它会火的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(),因为的onCreate(), ONSTART() onResume()将被调用时,启动活动。

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类启动另一个线程做一些工作,那么你必须有标志工作的方法。如果您的活动需要自动启动线程第一次执行,那么你必须将其套在一个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.

我们的想法是让你的活动设置一个布尔为true,要么你的应用程序实例或共享preferences 首先执行时的线程。当你回来的活动,不希望该线程将自动由于执行的onCreate()被称为那么你必须围绕包装你的电话code如果一些像这个例子子句如下:

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.

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

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