Android下多线程同UI交互的Handler框架代码
1 说明
Android开发过程中,使用多线程是一个很平常的事情,而多线程处理完成后,必然需要更新UI,本文略加整理,并附上框架代码,希望对大家有用。
2 内容
代码主要结构:
Activity代码文件
ProcessThread代码文件
其中Activity代码中创建了Handler msgHandler对象,并重载了handleMessage方法。
ProcessThread中的构造函数,需要传入msgHandler对象作为构造参数,在处理数据后,发送消息即可。在主Activity中的handleMessage就会收到消息。
3 项目代码
主Activity代码:
package com.jouhu.androidthreaduihandler;
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.widget.Button;
public class AndroidThreadUIHandlerActivity extends Activity {
public static final int RECV_DATA = 1;
Button btn = null;
ProcessThread pThread = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pThread = new ProcessThread(msgHandler);
}
});
}
private final Handler msgHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case RECV_DATA:
if(pThread != null)
{
byte[] data = pThread.getOneBuffer();
UpdateUI(data);
}
break;
}
}
private void UpdateUI(byte[] data) {
// TODO Auto-generated method stub
}
};
}
线程代码模型:
package com.jouhu.androidthreaduihandler;
import java.util.ArrayList;
import android.os.Handler;
import android.os.Message;
public class ProcessThread extends Thread {
private static final int BUFF_SIZE = 1024;
private Handler handler;
private ArrayList bytesList = null;
boolean running = true;
public ProcessThread(Handler handler)
{
this.handler = handler;
bytesList = new ArrayList();
}
public void run()
{
while(running)
{
//
byte[] buff = new byte[BUFF_SIZE];
Recv(buff,BUFF_SIZE);
Message msg = handler.obtainMessage(AndroidThreadUIHandlerActivity.RECV_DATA);
msg.obj = "Recv";
msg.sendToTarget();
}
}
private void Recv(byte[] buff, int buffSize) {
// TODO Auto-generated method stub
//可以处理Socket接收数据
}
public void AddOneBuffer(byte[]data)
{
//线程同步
synchronized(bytesList)
{
bytesList.add(data);
}
}
public byte[] getOneBuffer()
{
//线程同步
byte[] rdata = null;
synchronized(bytesList)
{
if(bytesList.size() > 0)
rdata = bytesList.remove(0);
}
return rdata;
}
}
4 源代码下载
模型代码下载:
AndroidThreadUIHandler
-END-
本文同发地址:http://doandroid.info/2012/03/15/android%E4%B8%8B%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%90%8Cui%E4%BA%A4%E4%BA%92%E7%9A%84handler%E6%A1%86%E6%9E%B6%E4%BB%A3%E7%A0%81/
欢迎转载,注明出处。