0

I am new to Android and I want to create an app that tracks the user location very frequently even the app is in background or killed. I have tested a lot of things like a foreground service but it is taking too much battery.

I want to track my user with Geofencing and the principle would be so :

I first takes the user location, I create a geofence around this location with TRIGGER_EXIT and a radius of 20meters, and each time TRIGGER_EXIT is trigger, I want to get the last known user location and create again a geofence around this location etc...

I started to implement this but I don't know how can I get the last known user location in a broadcast receiver and create a geofence in it.

I followed exactly the android tutorial on Geofence : https://developer.android.com/training/location/geofencing

public class GeofenceBroadcastReceiver extends BroadcastReceiver {
    // ...
    public void onReceive(Context context, Intent intent) {

         //Here is where I want to get a location point and add a geofence around this point
    }
}

Also, do you think my solution with geofence is a good choice to track my user?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • There is no other way that I'm aware of to keep your app running other than a sticky service. If it's using too much battery then maybe you could turn down either the frequency or accuracy of the GPS location requests. Another thing you could do is set a `Handler` with a long delay ... this would also reduce battery consumption. It's possible that your app is constantly checking multiple times a second, burning battery https://stackoverflow.com/questions/15874117/how-to-set-delay-in-android i'd need to see more code to break it down more for you. but the idea is invoke GPS less – hexagod Oct 17 '19 at 21:16
  • Thanks for your response. For the code i followed exactyly this Github repository for my foreground service : https://github.com/android/location-samples/tree/master/LocationUpdatesForegroundService. I tried to reduce the Accuracy of my location request to invoke less GPS but it seems that i dont get locations Update frequently with this Accuracy – Sofiane Bensliman Oct 18 '19 at 08:45
  • can you try something like this `Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);` instead of the broadcast receiver? My guess is that method is getting invoked a ton of times and the over invocation is draining your battery. Maybe try something like the second answer in this post: https://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android. Create a timer loop every few secs/mins that gets location – hexagod Oct 18 '19 at 14:48

0 Answers0