我需要做些什么才能让我的LocationListener触发onLocationChanged方法?
我是这个东西的新手(java和android)。这就是我在做的事情。 我通过调用context.startService(serviceIntent)处理位置请求; 在intent服务中,我有一个嵌套类作为LocationListener 在onHandleIntent方法的一侧,我启动一个请求位置更新的线程 我在OnHandleIntent方法中维护对LocationListener对象和脚踏的引用。
我的计划是onLocationChanged方法更新一个变量,我可以定期查看该变量是否已完成更新,然后断开循环并对该位置做一些事情。
问题是永远不会调用onLocationChanged方法。 LocationListener对象在onHandleIntent方法的末尾仍然有效。 我甚至可以直接调用它并获得我期望的调试消息。 我很确定DDMS正在改变位置,因为我已经在各种调试日志中打印出来了,我发现它正在发生变化。
以下是代码:
package com.example.locationrequestreceiver;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
public class LocationRequestService extends IntentService {
private LocationManager locationManager;
public class UpdateHandler implements Runnable, LocationListener {
@Override
public void onLocationChanged(Location arg0) {
Log.d("myStuff", "inside location changed");
}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
Log.d("myStuff", "inside thread");
locationManager.requestLocationUpdates("gps", 0, 0, this);
Log.d("myStuff", "run ending");
Looper.loop() // <--- this was the fix
}
}
public LocationRequestService() {
super("LocationRequrestService");
Log.d("myStuff", "inside the service");
}
@Override
protected void onHandleIntent(Intent arg0) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
UpdateHandler update_handler = new UpdateHandler();
Thread update_handler_thread = new Thread(update_handler);
Log.d("myStuff", "starting thread");
update_handler_thread.start();
for (int count = 0; count < 20; count++) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
Location location = locationManager.getLastKnownLocation("gps");
update_handler.onLocationChanged(location);
}
}