大家好我們這一節講的是Android Handler的使用,在講Handler之前,我們先提個小問題,就是如何讓程式5秒鐘更新一下Title.
首先我們看一下習慣了Java程式設計的人,在不知道Handler的用法之前是怎麼樣寫的程式,程式碼如下所示:
[java] android_tutor/article/details/5568806#" target="_blank">view plain
android_tutor/article/details/5568806#" target="_blank">copy
- 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執行不同的任務。
所以我們修改後的程式碼如下:
[java] android_tutor/article/details/5568806#" target="_blank">view plain
android_tutor/article/details/5568806#" target="_blank">copy
- 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 ++;
- }
- }
本文來自新浪部落格