参考:转:Thread和Looper以及Handler和Message详解 Android开发必读
像提示说的,添加 Looper.prepare();
Thread action=newThread() {
publicvoidrun() {
Looper.prepare();
todo();
Looper.loop(); } }; action.start()
解决办法二:使用handler
参考:http://mycoding.javaeye.com/blog/882756
在主activity中定一个Handler的成员,然后实现handlemassage函数,创建线程后在runable的run函数里new一个message,然后指定message对象的what成员,这个是指定message的一个id,然后在run中调用Handler的成员,使用其成员方法中的sendmessage(好像是叫这个),handlemassage函数中参数有个massage,根据该message参数中的what来对你发送message时指定的what来处理UI的功能
private
Handler mHandler
=
new
Handler(){
public
void
handleMessage(Message msg) {
switch
(msg.what)
{
case
ID_USER:
//
获取传递的数据
//
Bundle data = msg.getData();
//
int count = data.getInt("COUNT");
//
处理UI更新等操作
} };
};
主activity中创建线程 Java code
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->
MyThread thread
=
new
MyThread();
mThread
=
new
Thread(thread);
mThread.start();
MyThread Java code
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->
class
MyThread
implements
Runnable {
public
void
run() {
//
执行数据操作,不涉及到UI
Message msg
=
new
Message();
msg.what
=
ID_USER;
//
这三句可以传递数据
//
Bundle data = new Bundle();
//
data.putInt("COUNT", 100);
//
COUNT是标签,handleMessage中使用
//
msg.setData(data);
mHandler.sendMessage(msg);
//
向Handler发送消息,更新UI
}
|