重新启动活动时线程继续

时间:2013-11-25 09:43:41

标签: java android multithreading

我有一个简单的主要活动,它包含一个更新时间并将其显示在UI上的线程。这是:

        final Runnable runnableTime = new Runnable() {
        @Override
        public void run() {
            {
                Date d = new Date();
                CharSequence timeString = DateFormat.format(
                        "hh: mm: ss -- d/MM/yyyy ", d.getTime());
                infoEntries.get(0).setDetails((String) timeString);
                c2_adapter.notifyDataSetChanged();
                System.out.println(timeString);
                handler.postDelayed(this, 1000);
            }
        }
    };
    handler.post(runnableTime);

现在我的问题是当我使用这种方法重启活动时:

    public void restart() {
    finish();
    startActivity(getIntent());
}

活动重新启动就好了,但我现在在后台运行了2个相同的线程,并且不再在UI上更新时间。

我尝试创建自己的Runnable,为我扩展Runnable,以便能够在重启时终止runnable。但这只会引发更多问题。

我以这种方式覆盖了这些方法:

    public void restart() {
    finish();
    startActivity(getIntent());
}

@Override
public void onResume(){
    super.onResume();
    handler.post(runnableTime);
}

@Override
public void onPause(){
    super.onPause();
    handler.removeCallbacks(null);
}

这是在on create方法中调用的时间项,也在teh timer ^:

        Date d = new Date();
    CharSequence timeString = DateFormat.format("hh: mm: ss -- d/MM/yyyy ",
            d.getTime());

    infoEntries.add(new ConsoleItem((String) timeString));

有人有解决方案吗?

提前感谢您的时间:)

3 个答案:

答案 0 :(得分:0)

首先,你没有任何线程(只有ui线程)。 其次,如果你开始做某事,你应该把它停在某个地方。

所以,将此handler.post(runnableTime);移动到Activity的onResume方法,并在Pause方法上将handler.removeCallbacks(runnableTime);添加到Activity。

答案 1 :(得分:0)

根据@blackbelt的回答

您的活动中的

会覆盖onPause方法

@override
public void onPause()
{
    handler.removeCallbacks(runnableTime );
}

答案 2 :(得分:0)

由于您丢失了对UI的引用,因此UI中的时间未更新。此外,最好在run方法中使用sleep()进行while循环,以处理时间进度,并在onPause()活动上退出while循环。例如,它可能是

boolean running = false;
    while (running) {
        // TODO do your stuff
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

开始计算电话之前

running=true;

和活动onPause()

running=false;

通过这种方式,您将处理何时启动runnable,它将在活动暂停/

上停止
相关问题