Android Handler 用法

本文详细解析了AndroidHandler的工作机制,包括如何发送和处理Message与Runnable对象,通过一个实例展示了如何在Activity中利用Handler实现线程间通信,以及如何通过Handler控制UI组件,同时强调了Handler在不同线程之间的正确使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[b]Android handler[/b]
根据Android API DOC:Android Handler主要用于发送和处理和一个线程有关联的消息队列(MessageQueue)的消息和可运行对象。从这句话中可以知道Handler发送和处理的对象有两个:Message 和 Runnable对象。每个Handler实例和一个线程和这个线程的消息队列相关联。当然队列的特点就是先进先出的原则。
有下面的例子说明处理的它的两个操作对象:

package com.daisy.android.network;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
*@author Andrew.Lee
*@create 2011-6-7 下午02:23:11
*@version 1.0
*@see
*/

public class HandlerActivity extends Activity implements OnClickListener {
private static String TAG = "System.out";
private Button start;
private Button end;
private ProgressBar progress;
private Button progress_button;
private Button progress_pause;
private Handler handler;
private Myhandler Myhandler;
private boolean threadTerminal = false;
private EditText editText;
private TextView textView;

public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.handler);
findView();
// define a handler
handler = new Handler();
// Output Acitvity thread info
Log.i(TAG, "Activity Thread id:" + Thread.currentThread().getId());
Log.i(TAG, "Activity Thread name:" + Thread.currentThread().getName());

}

public void findView() {
editText = (EditText) findViewById(R.id.entry);

start = (Button) findViewById(R.id.start);
start.setOnClickListener(this);

end = (Button) findViewById(R.id.end);
end.setOnClickListener(this);
progress = (ProgressBar) findViewById(R.id.progress);

progress_button = (Button) findViewById(R.id.progress_button);
progress_button.setOnClickListener(this);

progress_pause = (Button) findViewById(R.id.pause);
progress_pause.setOnClickListener(this);

textView = (TextView) findViewById(R.id.display);

}

class Myhandler extends Handler {
public void handleMessage(Message msg) {
Log.i(TAG, "Handler process...");
Log.i(TAG, "Handler Thread id:" + Thread.currentThread().getId());
Log.i(TAG, "Handler Thread name:"
+ Thread.currentThread().getName());
int count = msg.getData().getInt("count");
String str = msg.getData().getString("display");
if (count <= 100)
progress.setProgress(count);
else
progress.setVisibility(View.GONE);
Log.i(TAG, "Handler Thread ---(##)---" + str);
textView.setText("Handler Thread ---(##)---" + str);
}

}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch (id) {
case R.id.start:
Log.i(TAG, "You just press the start button");
// associate with the runnable r, create runnable and add into the
// message queue
handler.post(r);
break;
case R.id.end:
Log.i(TAG, "You just press the end button");
// associate with the runnable r, remove the pending posts in the
// message queue
handler.removeCallbacks(r);
break;
case R.id.progress_button:
Log.i(TAG, "You just click the progress button");
progress.setVisibility(View.VISIBLE);
Myhandler = new Myhandler();
if (!threadTerminal && !handelrThread.isAlive())
handelrThread.start();
break;
default:
Log.i(TAG, "You just ...");

}
}

Thread handelrThread = new Thread() {
int count = 0;

@Override
public void run() {
// TODO Auto-generated method stub
Log.i(TAG, "Start the thread...");
Log.i(TAG, "HandlerThread Thread id:"
+ Thread.currentThread().getId());
Log.i(TAG, "HandlerThread Thread name:"
+ Thread.currentThread().getName());
while (count < 101) {
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

count += 10;
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt("count", count);
bundle.putString("display", editText.getText().toString());
msg.setData(bundle);
Myhandler.sendMessage(msg);
Log.i(TAG, "the count is :" + count);
}
threadTerminal = true;
}
};

Runnable r = new Runnable() {

@Override
public void run() {
// post after delay 3 seconds
Log.i(TAG, "update for every 3 seconds");
// Output Runnable thread info
Log.i(TAG, "Runnable Thread id:" + Thread.currentThread().getId());
Log.i(TAG, "Runnable Thread name:"
+ Thread.currentThread().getName());
textView.setText("Text ---(^o^)---Runnable:"
+ editText.getText().toString());
handler.postDelayed(r, 3000);
}

};

}

上面的例子部分引用 http://www.iteye.com/topic/1062942
使用Start-end button 来说明对Runnable对象的处理和操作
使用ProgressBar 来说明对消息Message的发送和处理。
从上面的例子中发现:
1. Activity、Runnable r、handler 和 Myhandler 都是运行在Activity 主线程中,所以他们都可以对Activity中的UI组件进行设置操作。
2. handelrThread 不是在主线程中,它只能获取UI组件的信息,但是不能对UI组件进行Set操作,或者布局的处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值