Android提供了Invalidate方法实现界面刷新,但是Invalidate不能直接在线程中调用,因为他是违背了单线程模型:Android UI操作并不是线程安全的,并且这些操作必须在UI线程中调用。
Android界面刷新方法有两种,分别是利用Handler和利用postInvalidate()来实现在线程中刷新界面。
利用Handler刷新界面
实例化一个Handler对象,并重写handleMessage方法调用invalidate()实现界面刷新;而在线程中通过sendMessage发送界面更新消息。
[代码]java代码:
02 | new Thread( new GameThread()).start(); |
05 | Handler myHandler = new Handler() { |
07 | public void handleMessage(Message msg) { |
09 | case Activity01.REFRESH: |
10 | mGameView.invalidate(); |
13 | super .handleMessage(msg); |
17 | class GameThread implements Runnable { |
19 | while (!Thread.currentThread().isInterrupted()) { |
20 | Message message = new Message(); |
21 | message.what = Activity01.REFRESH; |
23 | Activity01. this .myHandler.sendMessage(message); |
27 | catch (InterruptedException e) { |
28 | Thread.currentThread().interrupt(); |
使用postInvalidate()刷新界面
使用postInvalidate则比较简单,不需要handler,直接在线程中调用postInvalidate即可。
[代码]java代码:
01 | class GameThread implements Runnable { |
03 | while (!Thread.currentThread().isInterrupted()) { |
07 | catch (InterruptedException e) { |
08 | Thread.currentThread().interrupt(); |
12 | mGameView.postInvalidate(); |