Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Q - Start foreground location service from the background

I'm not sure what the behaviour should be in this case.

In the documentation it says that:

An app is considered to be accessing location in the background unless one of the following conditions is satisfied:

  • An activity belonging to the app is visible.
  • The app is running a foreground service that has declared a foreground service type of location.

In the example provided by google, they use an Activity which starts a foreground service in the foreground:

https://github.com/android/location-samples/tree/master/LocationUpdatesForegroundService

In my case, I need to start tracking locations once a bluetooth device is connected to my device (Using a manifest-registered broadcast receiver) - which could be in the background, or after the app terminated).

So, I'm declaring the service in the manifest like they say:

 <service
       android:name=".MyForegroundService"
       android:foregroundServiceType="location"
       android:exported="false" />

The question is:

In the event when my app receive the broadcast, while in background / terminated - If I start the foreground service then, Is it considered accessing location in the background or accessing location in the foreground?

Should I request for ACCESS_BACKGROUND_LOCATION? or ACCESS_COARSE_LOCATION should be enough in this case?

like image 692
dor506 Avatar asked Mar 03 '23 00:03

dor506


1 Answers

On API 29, if you have an android:foregroundServiceType of "location", you do not need ACCESS_BACKGROUND_LOCATION. Any location access made while that Service is running is considered a "foreground access".

But that assumes you can get the foreground service running. You must be continuing a user-initiated action of some sort. If the Service is already running, then it won't be a problem; the Service represents the continuation of a user-initiated action. If you need to start it when the BT device connects, well, I'm not sure if that qualifies. That may not work. (If you find out... please suggest an edit!)

An example of an app that needs the ACCESS_BACKGROUND_LOCATION permission would be one that monitors your GPS position while no Activities are visible, and no "location"-type foreground service notifications are showing. On Android Q, this wouldn't be allowed to carry on for very long (more than about 30 seconds), without the permission.

I believe the OS also assigns ACCESS_BACKGROUND_LOCATION to legacy apps where the user has elected to "Allow all the time" on the location permission dialog.

like image 83
greeble31 Avatar answered Mar 05 '23 19:03

greeble31