我想在我的应用程序中每隔几秒钟做一些事情,为此,我已经通过以下代码实现了HandlerThreadhandler

handlerThread = new HandlerThread(getClass().getSimpleName());
        handlerThread.start();

    handler = new Handler(handlerThread.getLooper(), new Callback() {

        @Override
        public boolean handleMessage(Message msg) {

            //my code here
            return l.this.handleMessage(msg);
        }
    });


我通过从onCreate()发送消息来启动此处理程序

我处理以下消息:

private boolean handleMessage(Message msg) {
    switch (msg.what) {
        default:
            return false;
        case MY_MESSAGE:
            if(handler_stop==0)
            {
                checkLauncher();
                sendMessage(MY_MESSAGE); // I Send the message from here to make //this continuous
            }



    }

    return true;
}


它工作正常,但是它发送消息的速度太快了,我的意思是一直不断,相反,我希望此消息在2或3秒后发送,简而言之,我想每2-3秒重复一次任务。

我该如何在上面的代码上执行此操作?请一些帮助

最佳答案

首先为Handler声明一个全局变量,以从Thread更新UI控件,如下所示:

Handler mHandler = new Handler();


现在创建一个线程,并使用while循环使用线程的sleep方法定期执行任务。

new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(10000);// change the time according to your need
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            // Write your code here to update the UI.
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }).start();


否则,只需在您的代码中添加以下内容即可:

handler.postDelayed(new Runnable(){
        public void run() {
          // do something
      }}, 20000);

09-30 15:01
查看更多