Android - 在计时器内重复运行一个线程

时间:2012-07-24 21:01:43

标签: android multithreading timer repeat

首先,我甚至无法选择使用该方法,我现在正在阅读几个小时,有人说使用'处理程序',有人说使用'计时器'。这是我试图实现的目标:

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

这是我的代码:

检查是否选中了复选框,如果选中'refreshAllServers'void将执行,这将执行带有计时器的作业。

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:

public void refreshAllServers(String start) {

    if(start == "start") {

        // Start the timer which will repeatingly execute the thread

    } else {

        // stop the timer

            }

这就是我执行我的线程的方式:(没有计时器就可以正常工作)

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

我尝试了什么?

我尝试过任何我可以从谷歌(处理程序,计时器)看到的例子,没有一个工作,我设法启动计时器一次,但停止它不起作用。 最简单的&我在研究中看到的可理解的代码是:

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

5 个答案:

答案 0 :(得分:35)

只需使用以下代码段

即可
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);

应该做的伎俩。

答案 1 :(得分:2)

感谢大家,我使用Timer解决了这个问题。

timer = new Timer();
timer.scheduleAtFixedRate(
    new java.util.TimerTask() {
        @Override
        public void run() {
            for (int i = 0; i < server_amount; i++) {

                servers[i] = "Updating...";
                handler.sendEmptyMessage(0);
                new MyThread(i).start();
            }
        }
    },
2000, 5000);

答案 2 :(得分:1)

我会考虑使用AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html

如果复选框处于通话方法

AlarmManager alarmManager = (AlarmManager)SecureDocApplication.getContext()
    .getSystemService(Context.ALARM_SERVICE);
PendingIntent myService = PendingIntent.getService(context, 0, 
                new Intent(context, MyService.class), 0);

long triggerAtTime = 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, 5000 /* 5 sec*/, 
                myService);

如果复选框已关闭取消警报管理器

alarmManager.cancel(myService);

答案 3 :(得分:1)

使用CountDownTimer。它的工作方式是在定时器的每个刻度上调用一个方法,在定时器结束时调用另一个方法。此时您可以根据需要重新启动。另外我认为你应该开始使用AsyncTask而不是线程。请不要尝试在Android中管理自己的主题。请尝试以下方式。它的运行就像一个时钟。

 CountDownTimer myCountdownTimer =    new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     // Kick off your AsyncTask here.
 }

 public void onFinish() {
     mTextField.setText("done!");
     // the 30 seconds is up now so do make any checks you need here.
 }
 }.start();

答案 4 :(得分:0)

“[ScheduledThreadPoolExecutor]类优于Timer,当需要多个工作线程时,或者需要ThreadPoolExecutor(此类扩展)的额外灵活性或功能时。”

...每

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

它不仅仅是处理程序,而是可以选择经常运行(每次计算完成后延迟)。

foo = [+, -, /, *]