利用Handler重新整理介面
執行個體化一個Handler對象,並重寫handleMessage方法調用invalidate()實現介面重新整理;而線上程中通過sendMessage發送介面更新訊息。
- // 在onCreate()中開啟線程
- new Thread(new GameThread()).start();、
-
-
- // 執行個體化一個handler
- Handler myHandler = new Handler()
- {
- //接收到訊息後處理
- public void handleMessage(Message msg)
- {
- switch (msg.what)
- {
- case Activity01.REFRESH:
- mGameView.invalidate(); //重新整理介面
- break;
- }
- super.handleMessage(msg);
- }
- };
-
-
- class GameThread implements Runnable
- {
- public void run()
- {
- while (!Thread.currentThread().isInterrupted())
- {
- Message message = new Message();
- message.what = Activity01.REFRESH;
- //發送訊息
- Activity01.this.myHandler.sendMessage(message);
- try
- {
- Thread.sleep(100);
- }
- catch (InterruptedException e)
- {
- Thread.currentThread().interrupt();
- }
- }
- }
-
- }
使用postInvalidate()重新整理介面
使用postInvalidate則比較簡單,不需要handler,直接線上程中調用postInvalidate即可。
- class GameThread implements Runnable
- {
- public void run()
- {
- while (!Thread.currentThread().isInterrupted())
- {
- try
- {
- Thread.sleep(100);
- }
- catch (InterruptedException e)
- {
- Thread.currentThread().interrupt();
- }
- //使用postInvalidate可以直接線上程中更新介面
- mGameView.postInvalidate();
- }
- }
- }