Android - 在计时器内重复运行一个线程 [英] Android - Run a thread repeatingly within a timer

查看:24
本文介绍了Android - 在计时器内重复运行一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我什至无法选择要使用的方法,我现在阅读了几个小时,有人说使用处理程序",有人说使用计时器".这是我尝试实现的目标:

First of all, I could not even chose the method to use, i'm reading for hours now and someone says use 'Handlers', someone says use 'Timer'. Here's what I try to achieve:

在首选项中,有一个设置(复选框)可以启用/禁用重复作业.当该复选框被选中时,计时器应该开始工作并且线程应该每 x 秒执行一次.由于未选中复选框,计时器应停止.

At preferences, theres a setting(checkbox) which to enable / disable the repeating job. As that checkbox is checked, the timer should start to work and the thread should be executed every x seconds. As checkbox is unchecked, timer should stop.

这是我的代码:

检查复选框是否被选中,如果选中'refreshAllServers' void 将被执行,它使用计时器完成工作.

Checking whether if checkbox is checked or not, if checked 'refreshAllServers' void will be executed which does the job with timer.

boolean CheckboxPreference = prefs.getBoolean("checkboxPref", true);
                if(CheckboxPreference == true) {
                    Main main = new Main();
                    main.refreshAllServers("start");
                } else {
                    Main main = new Main();
                    main.refreshAllServers("stop");
                }

执行计时器工作的 refreshAllServers void:

The refreshAllServers void that does the timer job:

public void refreshAllServers(String start) {

    if(start == "start") {

        // Start the timer which will repeatingly execute the thread

    } else {

        // stop the timer

            }

这是我执行线程的方式:(无需计时器即可正常工作)

And here's how I execute my thread: (Works well without timer)

Thread myThread = new MyThread(-5);
                myThread.start();

我尝试了什么?

我尝试了可以​​从 Google 看到的任何示例(处理程序、计时器),它们都不起作用,我设法启动了一次计时器,但停止它不起作用.最简单的&我在研究中看到的可以理解的代码是这样的:

I tried any example I could see from Google (handlers, timer) none of them worked, I managed to start the timer once but stoping it did not work. The simpliest & understandable code I saw in my research was this:

new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
            }
        }, 
        5000 
);

推荐答案

只需使用下面的代码片段

Just simply use below snippet

private final Handler handler = new Handler();
private Runnable runnable = new Runnable() {
    public void run() {
         //
         // Do the stuff
         //

         handler.postDelayed(this, 1000);
    }
};
runnable.run();

停止使用

handler.removeCallbacks(runnable);

应该可以.

这篇关于Android - 在计时器内重复运行一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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