Types of location access
Android Q location permissions have the following categories of location access:
- Foreground Location Access
- Background Location Access
Foreground Location Access
If your application shares or receives the location for a one-time or particular amount of time then that feature requires foreground location access. Some examples are added below,
- Users get turn-by-turn directions in a navigation app.
- Users can share their current location with another user in a messaging app.
You need to declare the permissions for foreground access in manifest either “ACCESS_COARSE_LOCATION” permission or the “ACCESS_FINE_LOCATION” permission, as shown in the below snippet:
Background Location Access
When an app needs to share the location continuously with other users, it requires background location access. Some examples are included below:
- In a family location sharing app, the feature allows users to continuously share location with family members.
The level of sureness depends on which permission you request:
- ACCESS_COARSE_LOCATION It provides an accurate location within the city block.
- ACCESS_FINE_LOCATION It provides a more accurate location than one provided when you request “ACCESS_COARSE_LOCATION”. This permission is necessary for some other connectivity tasks like connecting to nearby devices over Bluetooth Low Energy (BLE).
The COARSE_LOCATION will pop up a dialog with the three options when you access the location.
- Allow Always On selecting “Allow Always”, the location is continuously shared with the user all the time, whether the app is either foreground or background.
- Allow only while using the app It shares user location only when the application is used. It stops the location sharing after the user closes the application.
- Deny While clicking “Deny”, it disables the location permission request but when you look for the location request for a second time it shows the fourth option - Deny & Do Not Ask Again.
Code
Code for the activity_main.xml
Code inside MainActivity.java
OnRequestPermissionResult check the location permission granted or not. On clicking the location permission button, it will ask you for foreground and background location access. If you do not select foreground access the loop will break. There is no use of background location access without giving a foreground location access.
I have attached the output of the above application below for reference.