【问题标题】:Thread, can't create handler inside thread that not called looper.prepare线程,无法在未调用 looper.prepare 的线程内创建处理程序
【发布时间】:2012-08-15 17:35:24
【问题描述】:

我在尝试调用时收到“无法在未调用 looper.prepare 的线程内创建处理程序”错误,

locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);

但是,如果我不在线程( run() )中调用它,它可以正常工作。我该怎么办?

编辑: MyAlarmService.java

private Handler handler = new Handler(){

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        System.out.println("Handle MSGGGGGGGGGG");

    }

};

@Override
public void onStart(Intent intent, int startId) {
 // TODO Auto-generated method stub
 super.onStart(intent, startId);

 WorkerThreads WT1 = new WorkerThreads("Thread1");
 WorkerThreads WT2 = new WorkerThreads("Thread2");
    WT1.start();
    WT2.start();
}

class WorkerThreads extends Thread{

    public WorkerThreads(String string) {
        // TODO Auto-generated constructor stub
        super(string);
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();

        if(getName().equals("Thread1")){
            System.out.println("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM");
            GetAlarmCoordinates gcc = new GetAlarmCoordinates();
            gcc.init(getApplicationContext(),handler);
            /*try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/

              System.out.println(MyAlarmService.currentLatLon[0] + "   " + MyAlarmService.currentLatLon[1] );

        }else if(getName().equals("Thread2")){

        }


    }


}

GetAlarmCoordinates.java

public void init(Context cont, Handler handler){

    mHandler = handler;
    locManager = (LocationManager) cont.getSystemService(Context.LOCATION_SERVICE);
    onClick();
}

 public void onClick() {
//  progress.setVisibility(View.VISIBLE);
    // exceptions will be thrown if provider is not permitted.
    System.out.println("GetCurrentLocation");
    try {
        gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }
    try {
        network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    System.out.println("gps_enabled : "+gps_enabled+ " network_enabled : "+network_enabled);


    if (gps_enabled) {
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
    }

    if (network_enabled) {
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
    }
}

     class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            // This needs to stop getting the location data and save the battery power.
            locManager.removeUpdates(locListener); 
            //locationManager.requestLocationUpdates(GPS_PROVIDER, intervall, distance, listener);


            latitude =  location.getLatitude();
            londitude = location.getLongitude();

            MyAlarmService.currentLatLon[0] = latitude;
            MyAlarmService.currentLatLon[1] = londitude;


            System.out.println("Alarm Coodinates lat : "+latitude+"  lon : "+londitude);
            mHandler.sendEmptyMessage(0);
        //notify();



        } 
    }

【问题讨论】:

  • 叶戈尔的回答是正确的。原因是你不能在非 UI 线程中执行这样的操作。
  • 我有一个 BG 服务,每 5 分钟调用一次,当警报被调用时,我需要做两件事。检查麦克风的噪音并检查位置。所以我创建了两个线程并调用了函数。那么只有这个错误发生了..如何在这种特殊情况下做到这一点?
  • 你唯一能做的就是在主线程中调用它,而不是自己创建一个。但是如果您必须创建一个线程,那么您可以使用 Egor 提供的方法在 UI 线程中运行它,或者使用 Handler 并使用 sendMessage() 传递结果;方法。
  • 您能否展示一些在线程中使用处理程序的示例。我在单独的课程中检查位置。从我称之为这个类的线程..

标签: android multithreading location handler looper


【解决方案1】:

你可以使用Activity.runOnUiThread()方法来避免这个异常,这里是sn-p:

activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
            }
        });

希望这会有所帮助。

【讨论】:

  • 感谢您的快速回复,是在服务中使用它吗?没有 UI 线程..
【解决方案2】:

我猜locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); 必须在 UI 线程中运行。

解决方案:

只需在 UI 线程中运行,无需创建新线程。

如果你正在跑步

`locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);`

来自另一个类,然后您可以通过活动实例运行代码:

activity.runOnUiThread(new Runnable() {

@Override
public void run() {
// Your code
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
});

我希望这会有所帮助。

【讨论】:

    【解决方案3】:

    您可以在 Context 中使用getMainLooper, 只需将上下文作为参数和用户 lopper 发送给您的班级

    locationManager.requestLocationUpdates(getProviderName(), time, meter, locationUpdateListener,context.getMainLooper());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多