App Inventor Extensions


Location Service Extension SDK 34 ready!

See the App Inventor Extensions document about how to use an App Inventor Extension.

For questions about this extension or bug reports please start a new thread in the App Inventor community. Thank you.

For feature requests please contact me by email. To be a sponsor of a new method already is possible starting from only 10 USD! With your contribution you will help the complete App Inventor community. Thank you.

Jan 12th, 2021: Version 1: initial version for App Inventor.

Jan 26th, 2021: Version 1a: new keyword URIENCODEDATETIME added

Jan 28th, 2021: Version 1b: new keyword URIENCODECURRENTADDRESS added, new method IsRunning added, properties now return the previously stored values after restarting the app

Jul 15th, 2022: Version 2: property 'Post' renamed to 'RequestText', new property 'RequestMethod' added, valid values are GET, POST, PUT, DELETE, PATCH, HEAD or OPTIONS, new methods IsLocationBackgroundPermissionGranted and RequestLocationBackgroundPermission added. Thank you Lucas for being the sponsor of version 2.

Sep 27th, 2022: Version 3: SDK31 update: FLAG_IMMUTABLE for pending intents added, property MaxTimeBeforeShutdown in minutes added, RequestMethod helper added, bug fix for empty request header

Apr 7th, 2023: Version 3a: fused location provider replaced by gps to get precise location, automatic shutdown of service if gps is not available anymore

Apr 10th, 2023: Version 3b: no automatic shutdown if GPS is not available anymore, another location provider will be used in this case, which might have worse accuracy

Aug 22th, 2023: Version 4: SDK33 update: HasPostNotificationsPermission and OpenNotificationSettings methods added, permission android.permission.POST_NOTIFICATIONS added in Manifest

Jan 3rd, 2024: Version 4a: Extension rebuilt to avoid "ERROR: DX returned an error code" for projects, having 2 extensions or more which use proguard to obfuscate their code, see also Pull request 3004.

Jan 26th, 2024: Version 4b: Fix for Get requests

Mar 15th, 2024: Version 5: remove background web functionality and replace it by itoo integration, send always local broadcast, AskForPostNotificationsPermission method added

Mar 18th, 2024: Version 5a: new property NotificationTextLocked added

Apr 7th, 2024: Version 5b: itoox-wrapper included directly to avoid build conflict with other extensions, which also use itoox-wrapper.

Apr 10th, 2024: Version 5c: channelId changed to avoid conflict with other extensions, which use notifications.

Jun 30th, 2024: Version 6: SDK 34 update
Jul 25th, 2024: Version 6a: set RECEIVER_EXPORTED to enable LocationChanged event
(you can start using version 6 of the extension as soon as App Inventor targets SDK 34)

Description

Location Service Extension
This extension is able to run in the background while your app is closed and stores location data (latitude, longitude and optionally current datetime, altitude, accuracy, speed, current address and provider) in TinyDB.
Also using itoo you can execute almost any task in the background (no user interface components).
A notifier will be displayed while the location service is running in the background.
Minimum API level is 21 (Android 5).
Required permissions: android.permission.FOREGROUND_SERVICE, android.permission.ACCESS_FINE_LOCATION, android.permission.ACCESS_COARSE_LOCATION, android.permission.ACCESS_BACKGROUND_LOCATION, android.permission.INTERNET

Itoo integration

Itoo is a powerful framework to execute blocks in the background. Version 5 of the locationservice extension uses the new itoox-wrapper library and provides the new OnLocationChanged event handler (which looks like a procedure). By default the event handler is located in Screen1. But you can set the property ReferenceScreen (see documentation below) to use the event hanlder on a different screen.

The background event handler will be called from Itoo from the background after an a location changed event occurred. You will have to create the procedure using the name OnLocationChanged. Also that procedure must have 7 arguments, else it will not work. Note: This background event handler also will be called if the app is in the foreground.


Now we can execute almost any logic in the background (no user interface components) after a location changed event occurred. Please be aware, that there is no user interface available in the background.

Preconditions for using the OnLocationChanged event handler together with Itoo

  • You should already have some experience in App Inventor and understand the basics. If you are new, then first learn App Inventor and come back later for these advances features. Alternatively you can contact me by email to get personal support for a small fee. As beginner you already can use the lcationservice extension without the OnLocationChanged event handler!
  • You are familiar with the Do it debugging functionality of App Inventor.
  • You are familiar with using Logcat. To find possible errors of your blocks in the background, let me suggest to filter the logcat output for the tags TaifunLocationService, Notifier, ItooCreator and System.err.

Guidelines for using Itoo

  • First get your background functionality running in the foreground. Like this, you can find errors much easier. And as soon as you got it working in the foreground, then test it in the background.
  • Read the complete Itoo to leaarn how Itoo works and try the example projects, See also the battery checker tutorial and notification listener and itoo tutorial.
  • Do not use global variables while in the background, use local variables instead
  • Do not use any user-visible or UI components in the background
  • In the background, use the Itoo StoreProperty/FetchProperty methods rather than TinyDB. TinyDB relies on SharedPreferences which will not ensure data synchronization across background processes.

Kodular Restrictions

Properties


Reference screen for Itoo where the procedure 'OnLocationChanged' exists. If no property is set, the extension will take "Screen1" as the reference by default.

OnLocationChanged has the arguments latitude, longitude, altitude, accuracy, speed, currentAddress and provider.

Note: The OnLocationChanged event handler also will be called if the app is in the foreground!


Specifies whether location data should be stored locally in TinyDB. Default is true.



Determines the minimum time interval, in milliseconds, that the sensor will try to use for sending out location updates. However, location updates will only be received when the location of the phone actually changes, and use of the specified time interval is not guaranteed. For example, if 1000 is used as the time interval, location updates will never be fired sooner than 1000ms, but they may be fired anytime after.



Determines the minimum distance interval, in meters, that the sensor will try to use for sending out location updates. For example, if this is set to 5, then the sensor will fire a LocationChanged event only after 5 meters have been traversed. However, the sensor does not guarantee that an update will be received at exactly the distance interval. It may take more than 5 meters to fire an event, for instance.



Determines the maximum time in minutes before service will be shutdown automatically. Default is 0, which means no automatic shutdown.



The tag for TinyDB which should be used to store the location data. The value will be a table in CSV format, which contains the location data, see options below.
After a trip the collected location data could be used for example to display in a map.

Optional location data to be stored in TinyDB

As the collected data can be extensive, the following properties can be used to decide, if a specific location information should be stored in TinyDB or not.



Specifies whether the current datetime should be provided as result in TinyDB.



Specifies whether coordinates (latitude and longitude) should be provided as result in TinyDB.



Specifies whether current address should be provided as result in TinyDB.



Specifies whether accuracy should be provided as result in TinyDB.



Specifies whether altitude should be provided as result in TinyDB.



Specifies whether speed should be provided as result in TinyDB.



Specifies whether provider should be provided as result in TinyDB.

Notification properties

The following 5 properties are used to configure the notification, which will be displayed while the location service is running in the background. After the first location changed event occurred, the notification title and text then will be updated with the current location data. You can deactivate this behavior and lock the notification text. Just set property NotificationTextLocked to true.



SmallIcon for notification. Recommended size is 96x96.



Title to be displayed in the notification.



Text to be displayed in the notification.



Text to be displayed in the shutdown button of the notifier. Default value is 'Shutdown'.


Specifies whether notification should display constant text or current location data while running in the background. Default value is 'false'.

Methods


Start Service.
Note: You will have to build the app to be able to start the service.


Returns true, if basic location permissions have been granted, else false.


Returns true, if background location permission has been granted, else false.


Returns true, if post notifications permission has been granted, else false. This permission is available starting from API 33. For lower Android versions the method returns true.


Request Basic Location Permission.
Note: You will have to build the app to be able to request location permission.


Request Background Location Permission.
Note: Starting with Android 12 asking the user to grant location permission got again more complicated, see also this stackoverflow answer. The extension therefore offers 2 methods to ask for the required permissions.
Note: You will have to build the app to be able to request background location permission.


Ask for Post Notifications permission. Required starting from SDK 33.


Open Notification Settings for the user to allow posting notifications.

Android 6 to 9



The user needs to click "Allow" for the location service to be able to run.

Android 10



The user needs to click "Allow all the time" for the location service to be able to run in the background.

Android 11

On Android 11 (API level 30) and higher, however, the system dialog doesn't include the Allow all the time option anymore, see also here. Instead, users must enable background location on the settings page.

The extension offers the method RequestBackgroundLocationPermmission for that.


Move task (i.e. the app) to the background.


Shutdown Service.
Note: You will have to build the app to be able to shutdown the service.


Returns true, if location service is running in the background, else false.

Events


Indicates that a new location has been detected. Speed is reported in meters/second.
Note: This event only will fire if the app is up and running. In the background, please use the OnLocationChanged event handler.


Indicates that an Error occurred.


Indicates that service has been started.

Example 1 "Locationservice Test" without using Itoo

Blocks



Screenshots




Example 2 to send the location data to a MySQL database
while the location service is running in the background

For details how to use the web component to send data to a MySQL database, see my MySQL project here. I used the following CREATE TABLE statement:

      CREATE TABLE IF NOT EXISTS location(millis DECIMAL(13,0),
        lat FLOAT, lng FLOAT, address varchar(255), PRIMARY KEY(millis));
      


Example 3 to send location data to a Google Spreadsheet
while the location service is running in the background

a) using the web component

This example is based on the Google Spreadsheet example by TimAI2, Thank you Tim! First try the solution by Tim. After you get this running, then use my Spreadsheet example project, add your script url and try it. For easier testing use the ErrorOccured event of the locationservice extension and gotText event handler to find out, if the script has been setup correctly and receives the data correctly. After you get this running, then adjust it to your needs. Usually while using in the foreground it is sufficient to check property ShowListsAsJson in the properties of Screen1 to display lists in JSON format. This does not work in the background. Therefore we have to convert the list into JSON format manually there.




Example 3 to send location data to a Google Spreadsheet
while the location service is running in the background

b) using the spreadsheet component

This example uses the spreadsheet component Follow the setup steps and make sure, that you are successfully able to access the spreadsheet to add data. After you get this running, then use my Spreadsheet example project, add your spreadsheet id as well as your credentials json file and try it. For easier testing use the ErrorOccured event of the locationservice extension and finishedAddRow event handler to find out, if everything has been setup correctly and data is correctly added into the spreadsheet. After you get this running, then adjust it to your needs.



 

Test

Version 5 has been tested successfully on Samsung Galaxy A54 running Android 14.

Questions and Answers

Q1: Tips for getting your app approved for background location access
A: See this Google Blog, see also the Google Policy chapter Location Permissions.

Q2: I need to send latitude and longitude to firebase database in background. How can I do this with your extension?
A: Yes you can. There are 2 options now. 1) See this tutorial by TimAI2 how to send data to your Firebase database using the web component. Thank you Tim! After you are successfully able to use the web component to send data to your firebase database, then accordingly set up the OnLocationChanged event hander of the locationservice extension.
Alternatively use the FirebaseDB component directly. Starting from Verison 4.1 itoo is now able to directly access the Firebase database. See the itoo thread by Kumaraswamy how to send data to your Firebase database using the FirebaseDB component. Thank you Kumaraswamy! After you are successfully able to use the FirebaseDB component to send data to your firebase database, then accordingly set up the OnLocationChanged event hander of the locationservice extension.

For questions about App Inventor,
please ask in the App Inventor community.Thank you.

Test the functionality of the Location Service extension

The test app is available in Google Play. You can test the extension following these steps

  1. Read and agree to the Privacy Policy.
  2. Follow the opt-in URL for the locationservice example app to get access to the app and to be able to download it to your device. Here you can test all the features.
  3. Start testing.

Buy the Location Service extension for App Inventor


You can buy this extension (aix file).
With your payment you accept the terms and conditions below.

Payment options

1. Paypal

Please transfer 15 USD via Paypal
to Pura Vida Apps

PayPal - The safer, easier way to pay online!

2. Bitcoin

Then send me the transaction id by email and tell me the extension you are interested in.

After having received your payment I will be happy to send the download link to you. Please let me know your Google account! I usually will send the download link not later than 24 hours after having received your payment.
Thank you! Taifun


Terms and Conditions

Back to top of page ...


Home | Snippets | Tutorials | Extensions | Links | Search | Privacy Policy | Contact