大佬教程收集整理的这篇文章主要介绍了java – 如何在运行时更改android中的睡眠/计时器线程的延迟?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是代码
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 ends thread.start();//timer starts
如果你在网上搜索“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 counter timer.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中的睡眠/计时器线程的延迟?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。