不从IntentService调用onLocationChanged

时间:2015-07-09 16:56:07

标签: android android-intent gps alarm

我有一个每30分钟触发一次IntentService的AlarmManager,这个意图服务每次都会获取用户的位置。我有2种获取位置的方法:首先它检查getLastKnownLocation(),如果它在最后2分钟内使用它,这部分完美地运行

第二种方式是如果最后一个位置是旧的或返回null,我想在其中获取一次新位置。出于某种原因,这永远不会调用onLocationChanged()。这导致我的IntentService在很多时候都没有返回坐标,只有在getLastKnownLocation()是最近的时才返回它们。

这是我的代码如何设置,为什么如果我想获得一个新的位置,它永远不会被调用?检查代码中的注释,以查看调用的内容和从未调用过的内容。

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);
        }
    }

1 个答案:

答案 0 :(得分:1)

您应该使用服务而不是IntentService。完成任务后,IntentService完成,但服务正在运行并且可以监听位置更改事件。尝试使用服务。

希望它可以帮到你!!