zoukankan      html  css  js  c++  java
  • Android handler 报错处理Can't create handler inside thread that has not called Looper.prepare()

    问题:

    写了一个sdk给其他人用,提供一个回调函数,函数使用了handler处理消息

    // handler监听网络请求,完成后操作回调函数
            final Handler trigerGfHandler = new Handler() {
                public void handleMessage(Message msg) {
                    listener.onGeofenceTrigger(gfMatchIds);
                }
            };

    在使用这个sdk提供的函数时,报错:

    01-02 15:46:10.498: E/AndroidRuntime(16352): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

    使用方式是在service中使用。在activity中使用正常。

    问题解决:

    在调用handler的方法前执行Looper.prepare()。Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环起作用。

    因为activity的主线程是自己创建消息队列的,所以在Activity中新建Handler时,不需要先调用Looper.prepare()

    代码:

    Looper.prepare();
            // handler监听网络请求,完成后操作回调函数
            final Handler trigerGfHandler = new Handler() {
                public void handleMessage(Message msg) {
                    listener.onGeofenceTrigger(gfMatchIds);
                }
            };
    Looper.loop();

     参考:http://www.myexception.cn/mobile/410671.html

    ========================

    新问题:

    当此函数在activity中调用时,也会报错,因为activity已经自动创建了消息队列。所以重复创建会出错。

    查看官网关于Looper的例子:

    class LooperThread extends Thread {
          public Handler mHandler;
    
          public void run() {
              Looper.prepare();
    
              mHandler = new Handler() {
                  public void handleMessage(Message msg) {
                      // process incoming messages here
                  }
              };
    
              Looper.loop();
          }
      }

    将handler写在一个线程中。使此消息队列与主线程中消息队列分离。

    最终写法为:

    class LooperThread extends Thread {
                
                public void run() {
                    Looper.prepare();
                    trigerGfHandler = new Handler() {
                        public void handleMessage(Message msg) {
                            // process incoming messages here
                            listener.onGeofenceTrigger(gfMatchIds);
                        }
                    };
                    Looper.loop();
                }
            }
            
            LooperThread looper = new LooperThread();
            looper.start();
  • 相关阅读:
    python进程同步,condition例子
    python管道pipe,两个进程,使用管道的两端分别执行写文件动作,带锁(lock)
    无论怎样,拒绝了
    这两天发现又到了写无可写的地步
    用Perl编写Apache模块
    技术开发团队的项目管理工具
    *nix下传统编程入门之GCC
    当kfreebsd 用户遇见openSUSE系统
    kFreeBsd 国内开源镜像站汇总
    [转]编程语言与宗教
  • 原文地址:https://www.cnblogs.com/sudawei/p/3502074.html
Copyright © 2011-2022 走看看