Android高手進階教程(九)之----Android Handler的使用!!!

你們好咱們這一節講的是Android Handler的使用,在講Handler以前,咱們先提個小問題,就是如何讓程序5秒鐘更新一下Title.java

首先咱們看一下習慣了Java編程的人,在不知道Handler的用法以前是怎麼樣寫的程序,代碼以下所示:android

[java] view plain 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執行不一樣的任務。編程

 

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 ++;  
    }  
}

下面咱們看一下效果圖:app

相關文章
相關標籤/搜索