android

Handler.post(action) 这是android提供的一种机制,handler对象将通过post方法,将里面的Runnable对象放到UI执行队列中,UI消费这个队列,调用Runnable的run方法。这里并不生成新的线程。

Android中在绘图中的多线程中,invalidate和postInvalidate这两个方法是用来刷新界面的,调用这两个方法后,会调用onDraw事件,让界面重绘。

在一个没有使用线程的小游戏中想刷新一下时间进度,想到用Timer。于是写了一段代码:

nStartRoundTime = System.currentTimeMillis();
nT1 = new Timer();
nT1.schedule(new TimerTask(){ //计划运行时间间隔
public void run(){
refreshTimePaint(); //过3秒调用一下refreshTimePaint()
}
},0,3000);

public void refreshTimePaint(){
invalidate(); //使用invalidate();刷新
System.out.println(System.currentTimeMillis());
System.out.println(nGameState);
}

同时我也将System.currentTimeMillis()打印在View上。

运行一下,发现并不是预期那样, System.out.println的结果在Log里面都有变化,但是View却没有反应。 不但View上面没有被刷新,甚至连原来的触屏事件都没有反映了。

去网上查了一下,得到的一些解释有这些:

The best thing is to use Handler with delayed messages.
And Timer works fine, the problem is that a Timer runs in a separate thread, and so you are trying to modify a view owned by another thread (the main thread that originally created it).

What I think is happening is you're falling off the UI thread. There is a single "looper" thread which handles all screen updates. If you attempt to call "invalidate()" and you're not on this thread nothing will happen.

Try using "postInvalidate()" on your view instead. It'll let you update a view when you're not in the current UI thread.

于是把refreshTimePaint()的代码改成:

public void refreshTimePaint(){
this.postInvalidate(); //使用postInvalidate();刷新
System.out.println(System.currentTimeMillis());
System.out.println(nGameState);
}

这样View就能自动刷新了~~~

这里有几个网页做参考:

http://stackoverflow.com/questions/522800/android-textview-timer

http://groups.google.com/group/android-developers/browse_thread/thread/5baf5a3eaa823b7b?pli=1

http://groups.google.com/group/android-developers/msg/f5765705b8c59d66

更多相关文章

  1. android跨线程通信eventbus
  2. SONY 系列手机 Android 5.1 系统 Root 方法
  3. [置顶] 教程--Android SDK更新方法(2016.10.11更新)
  4. 关于Android Studio第一次启动的Fetching android sdk component
  5. Android中startService基本使用方法概述
  6. Android判断网络状态方法详解
  7. eclipse:运行 Android 项目时出现 “Unable to execute dex: Mult

随机推荐

  1. Android(安卓)issues
  2. Android(安卓)Path的使用
  3. Android重启应用程序代码
  4. android 杀进程方法
  5. android本地音乐播放(一)
  6. Android(安卓)发送无序广播
  7. android 工程源码下编译 Android.mk写法
  8. Android中HandlerThread的使用
  9. 15、android 常用文件路径备忘
  10. android 安装配置