简体   繁体   中英

How to avoid battery drainage if the app is using GPS even when the app is in background

I have to build an app that will have the following features :-

  1. A way to add users and their data in a database. (which will be parse)
  2. The app will access the location updates of the user (say after every 10 minutes or when the user has moved a significant distance). This will be done even when the app is in background. These locations will then be updated to the parse database as and when the new locations are received.

I am a beginner, so any suggestion to how i should approach this will be appreciated. Most importantly, i have the following problems :-

  1. The app will also run in the background and will regularly use GPS. This will drain a lot of battery. How can i avoid this? (The precision of the locations are important)

  2. The app will regularly update these locations to the parse database and will have to make regular API requests which will add to the cost. How can i minimise this?

From your description what you want is "significant location change" monitoring, which is built in to CLLocationManager . Instead of running continuous location updates, you tell the location manager to send you "significant" changes in location, ie when the user has moved some undocumented "significant" amount. It's specifically designed to minimize battery drain, so you don't need to bother disabling and reenabling it. Instead iOS makes sure you're using as little battery as possible to get the updates.

The CLLocationManager discuss the approach in some detail, but the basics are:

  • Once you've created your location manager, tell it to start significant location updates:

     locationManager.startMonitoringSignificantLocationChanges() 
  • Location changes are provided to the delegate via the same locationManager(manager:didUpdateLocations:) method used for continuous location updates.

  • iOS will wake your app up to let it process location updates.

You'll want to periodically update your location rather than leave GPS on continuously. Here's a tutorial covering CLLocationManager you may find helpful.

Without specific code, I can't give you a specific answer, but generally speaking you'll want to periodically turn on CLLocationManager , get your location, and turn it off again until the next update. You can also configure the accuracy of CLLocationManager --the more specific your location, the more battery power is required.

Here's another tutorial on CLLocationManager to take a peek at, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM