Android Handler定時更新UI

openkk 12年前發布 | 50K 次閱讀 Android Android開發 移動開發

     Handler在android里負責發送和處理消息。它的主要用途有:

        1)按計劃發送消息或執行某個Runnanble(使用POST方法);

        2)從其他線程中發送來的消息放入消息隊列中,避免線程沖突(常見于更新UI線程)

         默認情況下,Handler接受的是當前線程下的消息循環實例(使用Handler(Looper looper)、Handler(Looper looper, Handler.Callback callback) 可以指定線程),同時一個消息隊列可以被當前線程中的多個對象進行分發、處理(在UI線程中,系統已經有一個Activity來處理了,你可以再起若干個 Handler來處理)。在實例化Handler的時候,Looper可以是任意線程的,只要有Handler的指針,任何線程也都可以 sendMessage。Handler對于Message的處理不是并發的。一個Looper 只有處理完一條Message才會讀取下一條,所以消息的處理是阻塞形式的(handleMessage()方法里不應該有耗時操作,可以將耗時操作放在 其他線程執行,操作完后發送Message(通過sendMessges方法),然后由handleMessage()更新UI)。

參考 android.os.Handler 的文檔 
引用


There are two main uses for a Handler:  (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own. 


Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler). 


When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior. 



</div>

下面是個計數器演示代碼

Android Handler定時更新UI Android Handler定時更新UI


Java 代碼
package artray.cjp.counterdemo;

import android.app.Activity;  
import android.os.Bundle;  
import android.os.Handler;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.TextView;


public class CounterDemoActivity extends Activity {

    private Button btnStart;  
    private Button btnStop;  
    private Button btnReset;  
    private TextView tvCounter;  
    private long count = 0;  
    private boolean run = false;  
  
    private Handler handler = new Handler();  
  
    private Runnable task = new Runnable() {  
  
        public void run() {  
            // TODO Auto-generated method stub  
            if (run) {  
                handler.postDelayed(this, 1000);  
                count++;  
            }  
            tvCounter.setText("Count: " + count);  
        }  
    };  
  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
  
        btnStart = (Button) findViewById(R.id.Button01);  
        btnStop = (Button) findViewById(R.id.Button02);  
        btnReset = (Button) findViewById(R.id.Button03);  
        tvCounter = (TextView) findViewById(R.id.counter);  
  
        btnStart.setOnClickListener(new OnClickListener() {  
  
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
                run = true;  
                updateButton();  
                handler.postDelayed(task, 1000);  
            }  
        });  
  
        btnStop.setOnClickListener(new OnClickListener() {  
  
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
                run = false;  
                updateButton();  
                handler.post(task);  
            }  
        });  
  
        btnReset.setOnClickListener(new OnClickListener() {  
  
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
                count = 0;  
                run = false;  
                updateButton();  
                handler.post(task);  
            }  
        });  
    }  
  
    private void updateButton() {  
        btnStart.setEnabled(!run);  
        btnStop.setEnabled(run);  
    }  
}
</span>

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!