简体   繁体   English

更改活动时避免线程重新启动

[英]Avoiding threads restarting when changing activity

Right now, when I change the activity, my thread seams to go to sleep or something. 现在,当我更改活动时,我的线程会睡觉。 And when I come back to the main activity, there are two threads running, doing the same things. 当我回到主要活动时,有两个线程正在运行,并且执行相同的操作。 I'm not sure if this is the case, but it seems like it's something equal. 我不确定是否是这种情况,但这似乎是相等的。

...
public class MainActivity extends Activity {

public static double cowCount = 195;
public static double income = 0.100;
static boolean twiceCow = false, Threadrunning = false;
...
public void inc() {
    new Thread(new income()).start();
}

class income implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 20;) {
            final int value = i;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.post(new Runnable() {

                @Override
                public void run() {
                    cowCount = cowCount + income;
                    refresh();
                }
            });
        }
    }
}

This is how my thread looks like. 这就是我的线程的样子。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    handler = new Handler();
    checkThread();
}

private void checkThread() {
    if (Threadrunning == false)
    inc();
    Threadrunning = true;
}
public void inc() {
    new Thread(new income()).start();
}
...
public void refresh () {
TextView myTextView = (TextView)findViewById(R.id.myText);
myTextView.setText("You Have " + String.valueOf((nf.format(cowCount)) + " Cows!"));
}

I don't really understand what I've done wrong. 我不太了解自己做错了什么。

Please review this post: http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html 请查看这篇文章: http : //www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

Consider your activity re-start as the same thing as a config change. 重新启动活动与更改配置一样。

This pattern, ie using a retained Fragment as a container for your thread, and proxying UI updates via callbacks to your activity, is a pattern that will work much better for you. 这种模式,即使用保留的Fragment作为线程的容器,并通过对活动的回调来代理UI更新,这种模式将对您更好。

In your case you'd need only a single TaskCallback for your UI refresh(), eg onRefreshCowCount(int cows); 在您的情况下,您只需要一个TaskCallback来进行UI refresh(),例如onRefreshCowCount(int cows);

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

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