我有以下问题。我有这个实现我的线程与Looper。

public class GeoLocationThread extends Thread{

public Handler handler;
private General general;


public void run(){
    Looper.prepare();       
    handler = new IncomingHandler(general);
    Looper.loop();          

}

public GeoLocationThread(General general){
    this.general=general;
}



private static class IncomingHandler extends Handler{
    private final WeakReference<General> mService; 

    IncomingHandler(General service) {
        mService = new WeakReference<General>(service);
    }

    @Override
    public void handleMessage(Message msg)
    {
         General service = mService.get();
         if (service != null) {
             Location location=service.getLl().getLocation();
                if(location.getAccuracy()<40){                                                                                      
                    service.setOrigin(new GeoPoint((int) (location.getLatitude() * 1E6),(int) (location.getLongitude() * 1E6)));
                }
         }
    }

}

}

我想做以下事情:

GeoLocationThread locationThread=new GeoLocationThread(this);
locationThread.start();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll, locationThread.handler.getLooper());

其中lm是LocationManager。从我的日志和测试中,我可以这样说 locationThread.handler.getLooper() 返回null而不是Looper。

不知道为什么是null。我试过打电话 locationThread.isAlive() 这一切都变成了真的。我也试图得到 locationThread.handler; 我知道这不是空的。我也做了很多谷歌搜索,但我没有找到比documentaion更多。

在此先感谢您的回答.

有帮助吗?

解决方案

你的代码在读 null 很可能是因为操作两者彼此不同步。您无法成功呼叫 getLooper() 在一个 Handler 直到 Looper.prepare() 完成并构造处理程序。因为 Thread.start() 在另一个线程执行时不会阻塞(当然,为什么会呢?这将破坏新线程的目的)您已经在 run() 线程的块和试图设置位置侦听器的代码。这将根据谁可以首先执行在不同的设备上产生不同的结果。

此外,注册位置更新已经是一个异步过程,所以人们想知道为什么需要辅助线程?您可以简单地向侦听器请求更新,而无需传递辅助 Looper 当有新的更新可用时,侦听器将获得发布的数据,主线程在此过程中不会停留块。

其他提示

你必须在你的构造函数中调用super()吗?也许Looper没有被设置,因为父构造函数没有被调用?

好的,试试这个。做这个:

public class GeoLocationThread extends Thread{

是这样的:

public class GeoLocationThread extends HandlerThread{

那么你就可以做到这一点。getLooper()当您构造处理程序时或当您需要looper时。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top