【发布时间】:2015-09-28 04:50:29
【问题描述】:
我有一个AlarmManager,每30分钟触发一个IntentService,这个intent服务就是每次获取用户的位置。我有两种获取位置的方法:首先它检查 getLastKnownLocation(),如果它在最后 2 分钟内使用它,这部分工作得很好。
第二种方法是如果最后一个位置是旧的或返回null,我想在其中获取一次新位置。出于某种原因,这永远不会调用 onLocationChanged()。 这导致我的 IntentService 大部分时间都不会返回坐标,只有当 getLastKnownLocation() 是最近的时才会返回它们。
这是我如何设置它的代码,为什么如果我想获得一个新位置,它永远不会被调用?检查代码中的 cmets 以查看调用的内容和从未调用的内容。
LocationListener locationListener;
LocationManager locationManager;
private final double MIN_COORD_DIFF = 0.0006;
public CoordinateAlarmReceiver(){
super("CoordinateAlarmReceiver");
}
@Override
protected void onHandleIntent(Intent intent) {
//THIS IS CALLED CORRECTLY
MyLog.i("coordinate alarm received");
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//if last location was in past 2 minutes, use that
if(lastLocation != null && lastLocation.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
//THIS IS CALLED CORRECTLY
storeLocation(lastLocation);
MyLog.i("Last location was recent, using that");
}
else { //otherwise get new location
//THIS IS CALLED CORRECTLY
MyLog.i("Last location was old, getting new location");
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//THIS IS NEVER CALLED
MyLog.i("Got new coordinates");
storeLocation(location);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
【问题讨论】:
标签: android android-intent gps alarm