Can't create handler inside thread that has not called Looper.prepare()解决办法

参考:转: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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值