大家好我們這一節講的是android Handler的使用,在講Handler之前,我們先提個小問題,就是如何讓程序5秒鐘更新一下Title.
首先我們看一下習慣了Java編程的人,在不知道Handler的用法之前是怎麼樣寫的程序,代碼如下所示:
vIEw plaincopy to clipboardprint?
- package com.android.tutor;
- import Java.util.Timer;
- import Java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- public class HandlerDemo extends Activity {
-
- //title為setTitle方法提供變量,這裡為了方便我設置成了int型
- private int title = 0;
-
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentVIEw(R.layout.main);
-
- Timer timer = new Timer();
- timer.scheduleAtFixedRate(new MyTask(), 1, 5000);
- }
-
- private class MyTask extends TimerTask{
- @Override
- public void run() {
-
- setTitle("Welcome to Mr Wei's blog " + title);
- title ++;
- }
- }
- }
然而當我們執行程序,並不能達到我們預期的效果,所以android 引進了Handler 這個特殊的類,可以說它是Runnable和Activity交互的橋梁
,所以我們只要在run方法中發送Message,而在Handler裡,通過不同的Message執行不同的任務。
所以我們修改後的代碼如下:
vIEw plaincopy to clipboardprint?
- package com.android.tutor;
- import Java.util.Timer;
- import Java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- public class HandlerDemo extends Activity {
-
- //title為setTitle方法提供變量,這裡為了方便我設置成了int型
- private int title = 0;
-
- private Handler mHandler = new Handler(){
-
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1:
- updateTitle();
- break;
- }
- };
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentVIEw(R.layout.main);
-
- Timer timer = new Timer();
- timer.scheduleAtFixedRate(new MyTask(), 1, 5000);
- }
-
- private class MyTask extends TimerTask{
- @Override
- public void run() {
-
- Message message = new Message();
- message.what = 1;
- mHandler.sendMessage(message);
-
- }
- }
-
-
- public void updateTitle(){
-
- setTitle("Welcome to Mr Wei's blog " + title);
- title ++;
- }
- }
下面我們看一下效果圖: