如何按定义的时间间隔在Android中运行可运行线程? [英] How to run a Runnable thread in Android at defined intervals?

查看:229
本文介绍了如何按定义的时间间隔在Android中运行可运行线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个应用程序,用于在Android模拟器屏幕中按定义的时间间隔显示一些文本.我正在使用Handler类.这是我的代码的一个片段:

I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler class. Here is a snippet from my code:

handler = new Handler();
Runnable r = new Runnable() {
    public void run() {
        tv.append("Hello World");               
    }
};
handler.postDelayed(r, 1000);

当我运行此应用程序时,该文本仅显示一次.为什么?

When I run this application the text is displayed only once. Why?

推荐答案

您的示例的简单解决方法是:

The simple fix to your example is :

handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {
        tv.append("Hello World");
        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);

或者我们可以使用普通线程作为示例(使用原始Runner):

Or we can use normal thread for example (with original Runner) :

Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                handler.post(this);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();

您可以将可运行对象视为可以发送到消息队列以执行的命令,而将处理程序视为仅用于发送该命令的帮助对象.

You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.

更多详细信息在这里 http://developer.android.com/reference/android/os/Handler.html

这篇关于如何按定义的时间间隔在Android中运行可运行线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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