Search code examples
javaandroidgpslocation

onLocationChanged doesn't work while recording


Is there any way I can let GPS update every few seconds while using Record? I heard some articles say it needs to work in the foreground but I don't know how. I want it works in the background and record simultaneously.

  private void getLocal() {
    /**沒有權限則返回*/
    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
            checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    String localProvider = "";
    LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    /**知道位置後..*/
    Location location = manager.getLastKnownLocation(localProvider);
    manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mListener);
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener);
    if (location != null){
        longitude=location.getLongitude();
        latitude=location.getLatitude();
        Log.d("location", longitude.toString()+","+latitude.toString());
    }else{
        Log.d(TAG, "getLocal: ");
        manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mListener);
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener);
    }
}
/**監聽位置變化*/
LocationListener mListener = new LocationListener() {
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Override
    public void onLocationChanged(Location location) {
        longitude=location.getLongitude();
        latitude=location.getLatitude();
        Log.d("location", longitude.toString()+","+latitude.toString());
    }
};

Solution

  • You should manage the LocationManager (including requestLocationUpdates()) into the Application Class;
    Then you should use a Foreground Service (specifying android:foregroundServiceType="location") that implements a WAKE_LOCK to keep your Application working in background.

    You can read how to implement a foreground service here: Continuously get user location when app is paused or killed in android

    As alternative here you can browse a real working example on a free and opensource GPS Logging app.