消息机制相关API
Message(消息)
可理解为线程之间通讯的数据单元, 可以通过message携带需要的数据
创建对象: Message.obtain(what)
封装数据
public int what
public int arg
public Object obj
Handler(处理器)
Handler是Message的处理器, 同时也负责消息的发送和移除的工作
发送即时消息(马上发送, 马上处理): sendMessage(Message msg)
发送延迟消息(马上发送, 延迟处理): sendMessageDelayed(Message ms, long time)
处理消息: handleMessage(Message msg) (回调方法)
移除还没处理的消息(延迟消息还没被处理前, 可以继续移除): removeMessage(int what)
MessageQueue(消息队列)
用来存储通过Handler发送的消息
他是一个按Message的when排序的优先级队列(队列的特点是先进先出, 但是这里是按照优先级来排的)
Looper(钩子) 循环器
负责循环取出Message Queue 里面的当前需要处理的Message
交给对应的Handler进行处理
处理完后,将Message缓存到消息池中, 已备服用
测试用例
需求说明
1. 点击GET请求获取, 显示提示正在加载的进度条, 分线程请求网络
2. 得到数据后, 将数据显示到输入框中, 同时隐藏进度条
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/pb_handler1_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="invisible"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="getSubmit1"
android:text="GET Submit" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="getSubmit2"
android:text="GET Submit2" />
<EditText
android:id="@+id/et_handler1_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="显示结果" >
</EditText>
</LinearLayout>
测试无Handler的基本使用
1. 主线程, 显示提示视图(ProgressDialog/ProgressBar)
2. 分线程, 联网请求, 并得到响应数据
3. 主线程, 显示数据/隐藏提示视图
public class HandlerTestActivity extends Activity {
private ProgressBar pb_handler1_loading;
private EditText et_handler1_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_test);
pb_handler1_loading = (ProgressBar) findViewById(R.id.pb_handler1_loading);
et_handler1_result = (EditText) findViewById(R.id.et_handler1_result);
}
public void getSubmit(View v) {
//1. 主线程, 显示提示视图(ProgressDialog/ProgressBar)
pb_handler1_loading.setVisibility(View.VISIBLE);
//2. 分线程, 联网请求, 并得到响应数据
new Thread(){
public void run() {
String path = "http://192.168.10.165:8080/Web_Server/index.jsp?name=Tom&age=12";
try {
final String result = requestToString(path);
//3. 主线程, 显示数据
runOnUiThread(new Runnable() {
@Override
public void run() {
et_handler1_result.setText(result);
pb_handler1_loading.setVisibility(View.INVISIBLE);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 请求服务器端, 得到返回的结果字符串
* @param path : http://192.168.30.165:8080/Web_server/index.jsp?username=tom&age=12
* @return
* @throws Exception
*/
public String requestToString(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
String result = baos.toString();
connection.disconnect();
return result;
}
}
测试有Handler的基本使用
1. 创建Handler成员变量对象, 并重写其handleMessage()
2. 在分/主线程创建Message对象
3. 使用handler对象发送Message
4. 在handleMessage()中处理消息
public class HandlerTestActivity extends Activity {
private ProgressBar pb_handler1_loading;
private EditText et_handler1_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_test);
pb_handler1_loading = (ProgressBar) findViewById(R.id.pb_handler1_loading);
et_handler1_result = (EditText) findViewById(R.id.et_handler1_result);
}
//1. 创建Handler成员变量对象, 并重写其handleMessage()
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) { //在主线程执行
if(msg.what == 1) {
//4. 在handleMessage()中处理消息
String result = (String) msg.obj;
et_handler1_result.setText(result);
pb_handler1_loading.setVisibility(View.INVISIBLE);
}
}
};
public void getSubmit(View v) {
//1). 主线程, 显示提示视图(ProgressDialog/ProgressBar)
pb_handler1_loading.setVisibility(View.VISIBLE);
//2). 分线程, 联网请求, 并得到响应数据
new Thread(){
public void run() {
String path = "http://192.168.10.165:8080/Web_Server/index.jsp?name=Tom&age=12";
try {
String result = requestToString(path);
//3). 主线程, 显示数据
//2. 在分/主线程创建Message对象
Message message = Message.obtain();
message.what = 1;//标识
message.obj = result;
//3. 使用handler对象发送Message
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 请求服务器端, 得到返回的结果字符串
* @param path : http://192.168.30.165:8080/Web_server/index.jsp?username=tom&age=12
* @return
* @throws Exception
*/
public String requestToString(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
String result = baos.toString();
connection.disconnect();
return result;
}
}
应用DEMO
消息机制原理