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

来源:互联网 发布:c 高级编程第10版下载 编辑:程序博客网 时间:2024/06/06 12:27

参考:转: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的功能

privateHandler mHandler=newHandler(){ 
     publicvoidhandleMessage(Message msg) { 
           switch(msg.what)
    {
           caseID_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=newMyThread(); 
 mThread=newThread(thread); 
 mThread.start();

MyThread  
Java code
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->
classMyThreadimplementsRunnable { 
        publicvoidrun() {
            //执行数据操作,不涉及到UI 
            Message msg=newMessage(); 
            msg.what=ID_USER;
          //这三句可以传递数据 
          //Bundle data = new Bundle();
          //data.putInt("COUNT", 100);//COUNT是标签,handleMessage中使用
           //msg.setData(data);
          mHandler.sendMessage(msg);  //向Handler发送消息,更新UI
}
0 0
原创粉丝点击