I want to get the location of the device once when the service is running in the background (the tracker monitors the change in the database and then executes the code that should get the geolocation of the phone). I encountered a problem: the program receives location data when the application is running, but when it goes into the background, the location data stops being received in a few seconds. I tried all the codes and options that I could find, but everything stops working when the program goes into the background. For this I use AndroidStudio Java. So how do I implement this and is it even possible? Thanks.
CodePudding user response:
On Android there are two types of Services- foreground and background. Background (the default) on modern Android are killed 2 minutes after your app is no longer in the foreground. Foreground services are kept for longer, require you to have a notification so the user knows you're tacking him (think of Uber and the notification you can't swipe away you get while its running), but can still be killed for resources if other apps need it. You cannot rely on any Service running permanently.
So the answer is going to be either Foreground Service, or its going to be a completely different architecture for your program. The second really depends on exactly when and why you want to get the location.
CodePudding user response:
There are many limitations on getting on getting location in background, refer to this
- Do you target API level 29 or up? if yes, have you add
ACCESS_BACKGROUND_LOCATION
permission in manifest? If this is not declared, app can only access location while in foreground. - Even after declaring
ACCESS_BACKGROUND_LOCATION
permission, app can only get location data a few time in an hour due to limitations. Maybe you can consider using foreground service instead to avoid such limitations.