- new Thread()
- {
- public void run()
- {
- .....
- }
- }.start();
如果在上述代码中省略号处面创建一个Dialog的话会出现Can't create handle inside thread这样的错误,所以改用下述message形式的,下述是一个开发项目中具体的例子。
- private void showStatusDialogThread() {
- mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- if (status != null) {
- if (status.equals(SyncStatus.Success)) {
- // 更新本地保存的lastSyncTime为当前时间
- UpdateLocalLastSyncTime(System.currentTimeMillis());
- }
- showStatusDialog(status);
- mHandler.removeCallbacks(mRunnable);
- }
- super.handleMessage(msg);
- }
- };
- mRunnable = new Runnable() {
- @Override
- public void run() {
- mHandler.postDelayed(this, 100);
- Message message = new Message();
- mHandler.sendMessage(message);
- }
- };
- mHandler.post(mRunnable);
- }
其中
- showStatusDialog(status);
这种发送message的方式模型抽取出来就是下面的形式:
- {
- mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- //执行的具体方法,例如创建Dialog,计数等
- ......
- super.handleMessage(msg);
- }
- };
- mRunnable = new Runnable() {
- @Override
- public void run() {
- //设置延迟时间间隔
- mHandler.postDelayed(this, 100);
- Message message = new Message();
- mHandler.sendMessage(message);
- }
- };
- mHandler.post(mRunnable);
- }
然后在其他某处调用
- mHandler.removeCallbacks(mRunnable);
就可取消此message的发送。
其实这里发送message也是一种线程,相当于设置一个定时器,每隔一段时间执行某些代码一样。
下面是这个用法的另一个写法
我觉的更简单理解一些
Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); }
只需要在主线程调用delayedHide就可以实现
注:本文章参照http://blog.csdn.net/cangkukuaimanle/article/details/6937503