Android Handler.getLooper()返回null
我有以下问题。我有Thread Looper的这个实现。Android Handler.getLooper()返回null
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。
我不知道为什么它是空的。我曾尝试致电locationThread.isAlive()
,这已恢复正常。我也试图得到locationThread.handler;
,我知道它不是null。 我也做了大量的谷歌搜索,但我没有发现更多的文件。
非常感谢您提前为您的答案。
您的代码为null
很可能是因为操作二不相互同步。您无法在Handler
上成功拨打getLooper()
,直至完成Looper.prepare()
并构建处理程序。由于Thread.start()
在另一个线程执行时不会阻塞(当然,为什么它会阻止新线程的目的),因此您在线程的run()
块与尝试设置位置的代码之间创建了竞争条件监听器。这将根据谁可以先执行,在不同的设备上产生不同的结果。
此外,注册位置更新已经是一个异步过程,所以人们想知道为什么需要辅助线程?您可以简单地向侦听器请求更新,而无需传递第二个Looper
,并且在有新更新可用时侦听器将发布数据,主线程在此过程中不保留块。
您是否必须在构造函数中调用super()?可能是因为父构造函数没有被调用,Looper没有被设置?
好的,试试这个。使此:
public class GeoLocationThread extends Thread{
是这样的:
public class GeoLocationThread extends HandlerThread{
那么你可以做this.getLooper()当您构建处理程序,或者当您需要弯针。
我在代码中添加了行'super();',但我仍然从'locationThread.handler.getLooper()'中获得null。 – ziky90 2012-07-27 21:05:14
现在我不会从'locationThread.getLooper()'null null,但是GeoLocationThread似乎并没有像现在已经拦截所有其他东西的线程那样行为。 Looper是否应该停止其他一切? 顺便说一下,我现在在构造函数中应该具有什么作为super(String)的参数? – ziky90 2012-07-27 21:45:36
嗯,我认为它说它应该像一个线程一样工作,因为它扩展了Thread。奇怪。 Lwt我试着看看我能否重现它。 – Kaediil 2012-07-27 21:48:13
非常感谢你对我的帮助很大。 我只是重新实现它没有线程,它完美的作品。 – ziky90 2012-07-28 07:13:01