1 做不到那么精准的 系统调度和内部硬件中断都会影响
成都创新互联-专业网站定制、快速模板网站建设、高性价比武陵源网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式武陵源网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖武陵源地区。费用合理售后完善,10年实体公司更值得信赖。
2 SystemClock.sleep 源码上也是调用thread.sleep来的只是不会抛出异常在里面做了。
/**
* Waits a given number of milliseconds (of uptimeMillis) before returning.
* Similar to {@link java.lang.Thread#sleep(long)}, but does not throw
* {@link InterruptedException}; {@link Thread#interrupt()} events are
* deferred until the next interruptible operation. Does not return until
* at least the specified number of milliseconds has elapsed.
*
* @param ms to sleep before returning, in milliseconds of uptime.
*/
public static void sleep(long ms)
{
long start = uptimeMillis();
long duration = ms;
boolean interrupted = false;
do {
try {
Thread.sleep(duration);
}
catch (InterruptedException e) {
interrupted = true;
}
duration = start + ms - uptimeMillis();
} while (duration 0);
if (interrupted) {
// Important: we don't want to quietly eat an interrupt() event,
// so we make sure to re-interrupt the thread so that the next
// call to Thread.sleep() or Object.wait() will be interrupted.
Thread.currentThread().interrupt();
}
}
android 中,有的时候用Thread.sleep()是不合适的。
例如,你在用ProgressDialog 的时候,如果用的不合适,会使Progressdialog图标不转动。
代替方法是,用Handler.postDelayed需求是等2s,请求一下服务器。等待的时候,显示ProgressDialog 。
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendMessage("");//耗时操作
替换成
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
sendMessage("");//耗时操作
}
}, 2000);
子线程中不能操作UI元素, 你的线程中要更新TextView必须给主线程发消息的方式进行。
Handler handler = new Handler();
handler.postDelayed(这里写run方法实现一秒后的操作, 这里写时间1000);
是让程序进入暂停状态,使用Thred或者Run able都可以实现让程序进入Sleep状态