0

启动服务:

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, LocationService.class);
pi = PendingIntent.getService(this, 0, i,
        PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime(), 30*1000, pi);

服务:

public class LocationService extends Service implements LocationListener {

    public static double curLat = 0.0;
    public static double curLng = 0.0;
    private LocationManager mgr;
    private String best;
    private Location location;

    @Override
    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
        best = LocationManager.NETWORK_PROVIDER;
        location = mgr.getLastKnownLocation(best);
        if (location != null) {

            dumpLocation(location);
            mgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                    5 * 1000, 0, this);
        }
        return START_NOT_STICKY;
        }
    }

    private void dumpLocation(Location l) {

        SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy:hh:mm:ss",
                Locale.ENGLISH);
        String format = s.format(l.getTime());
        //The above time is always 21/03/2013:09:53:41 which is more than a week old
        curLat = l.getLatitude();
        curLng = l.getLongitude();
    }

    @Override
    public void onLocationChanged(Location location) {

        //This never seems to be called
        dumpLocation(location);
    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }
}

每 30 秒调用一次服务,但requestLocationUpdates似乎从不调用onLocationChanged。当我检查lastKnownLocation它一周前的时间时。

Foursquare、本地、地图等应用程序在禁用 GPS 的情况下提供当前位置。

我错过了什么?

4

1 回答 1

1

我认为您需要使用设备从某个地方移动,因为仅在位置更改时才调用 onLocationChange。并且网络位置大约在 1000-2000 米附近,因此需要检查位置发生变化的街道并获取新位置。如果您使用 gps,那么它会为您提供准确的信息,但在修复所有问题后,它也会在 20-30 米附近。

于 2013-03-29T07:12:18.150 回答