0

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());
    }
};
  • _"I heard some articles say it needs to work in the foreground but I don't know how. "_ The concept is [Foreground Service](https://developer.android.com/guide/components/foreground-services). Only the notification of the app needs to be "visible" (in the notification panel), not the whole UI. – Markus Kauppinen Oct 28 '22 at 13:00
  • Thanks, But I wonder how I can track my GPS every second when I am recording. What method should I use? – Liu Winny Oct 29 '22 at 10:16
  • You should use `requestLocationUpdates()` as you already do. – Markus Kauppinen Oct 31 '22 at 09:06

1 Answers1

1

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.

Graziano
  • 313
  • 1
  • 4
  • 11