java – 如何在运行时更改android中的睡眠计时器线程的延迟?

java – 如何在运行时更改android中的睡眠计时器线程的延迟?,第1张

概述我试图做的是每次计数器变为5的倍数时减少定时器延迟. 但是,一旦代码进入if块,它就会停止递增计时器. 我无法理解发生了什么. 这是代码 thread=new Thread(){ public void run(){ try{ if(count%5==0) timre--; else{ 我试图做的是每次计数器变为5的倍数时减少定时器延迟.
但是,一旦代码进入if块,它就会停止递增计时器.
我无法理解发生了什么.

这是代码

thread=new Thread(){    public voID run(){        try{            if(count%5==0)                timre--;            else{                //do nothing            }            //*******PROGRESS UPDATE********//            for(t=0;t<=100;t++) {                sleep((timre) / 100);                progress.setProgress(t);                t += 1;            }            //****PROGRESS UPDATE OVER****//        } catch (InterruptedException e) {            e.printstacktrace();        }        finally {            finish();        }    }//run ends};//thread endsthread.start();//timer starts
解决方法 Thread.sleep()不保证.这意味着它可能会或可能不会因您出于此问题的主题之外的各种原因而在您期望的时间内睡眠.

如果你在网上搜索“androID中的计时器”,你可能会登陆这两个:https://developer.android.com/reference/java/util/Timer.html和https://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html

您可以检查它们,但是,我不会使用它们,因为它们提供了许多其他功能,如名称所示(“ScheduledThreadPoolExecutor”).你不需要这个,因为这很可能被用于拥有大量线程等的大型系统……

如果我正确理解您的代码,您正在尝试更新进度条.
对于你想要做的事情,我建议使用一个处理程序.处理程序的主要用途之一是将消息和可运行程序安排为将来执行的某个点,如此处的文档中所指定的:
http://developer.android.com/reference/android/os/Handler.html

我会这样做:

int counter = 0; int delayInMs = 5000; // 5 seconds Handler timer = new Handler(new Handler.Callback() { @OverrIDe public boolean handleMessage(Message msg) {   counter++;   // If the counter is mod 5 (or whatever) lower the delay   if (counter % 5 == 0) {     delayInMs/=100; // Or any other calculation.   }    // If the counter reaches 100 the counting will not continue.   if (counter <= 100) {     // If the counter has not reached the condition to stop,the handler     // will call the timer again with the modifIEd (or not) delay.     timer.sendEmptyMessageDelayed(0,delayInMs);     // Change progress     updateProgress(counter);   }   return true; }});// ...// Somwhere in the code to start the countertimer.sendEmptyMessageDelayed(0,delayInMs); // starts the timer with the initial 5 sec delay.

还有一件事.在您拥有此代码的行中:

progress.setProgress(t);

从其他线程调用UI元素时要小心,这是很多头痛的根源.如果你的处理程序在另一个线程中,你应该将该调用包装在一个函数中,并确保从主线程(即UI线程)调用它.实现这一目标的许多方法(并非总是必要的).其中一个是这样的:

private voID updateProgress(int counter) {  WhateverActivity.this.runOnUiThread(new Runnable() {    public voID run() {      progress.setProgress(counter);    }  });}
总结

以上是内存溢出为你收集整理的java – 如何在运行时更改android中的睡眠/计时器线程的延迟?全部内容,希望文章能够帮你解决java – 如何在运行时更改android中的睡眠/计时器线程的延迟?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1148366.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存