- Performing Background Data Refresh for Android
- Introduction to Android Background Data Refresh
- Creating a Background Service
- Schedule the Background Data Refresh
- Configuration & Testing
- Wrapping Up
- How to turn off Background App Refresh on iPhone & Android to save phone data and battery
- What is Background App Refresh?
- Does Background App Refresh use data?
- ​Does Background App Refresh drain your battery?​
- How to turn off Background App Refresh on your iPhone and iPad
- How to turn off Background App Refresh on your Android
- How to turn off Background App Refresh for a specific app on your iPhone and iPad
- Protect your phone
- Фоновое выполнение приложений в iOS 13
- Вкратце о теме
- Что было на WWDC
- BackgroundTasks
- App Refresh Task
- Background Processing Task
- Отладка
- В заключение
Performing Background Data Refresh for Android
March 15th, 2016
Data is a crucial component of any app, which is why perfecting how your application interacts with data is so important. There are many techniques for improving interactions with remote data, such as request prioritization, speculative requests, and caching. These are certainly techniques to be explored and used, but what if your data was there before users even opened your app?
Both iOS and Android expose mechanisms for refreshing data when your app is in the background (i.e. when a user is using a different app on their mobile device). Previously, we covered how to perform background data refresh on iOS. In this blog post, we’re going to walk through the process of adding background data refresh to Android apps with the Google Cloud Messaging service in just a few easy steps.
Introduction to Android Background Data Refresh
Google Cloud Messaging (GCM) provides a way to send data between a client and server. However, it also exposes some additional functionality that we can take advantage of (even if you aren’t using GCM as a data service for your apps), such as the ability to schedule recurring background data refreshes at a regular interval. To get started, add the Xamarin Google Play Services – GCM NuGet to your project.
Android provides a mechanism for performing operations in the background called a service. Google Cloud Messaging exposes a special type of service named GcmTaskService which we can use to configure how exactly the background refresh will take place. We can then use the GcmNetworkManager to schedule a task on a regular interval.
Creating a Background Service
Create a new subclass of GcmTaskService named BackgroundService. All services must be marked with the [Service] attribute so that they can properly be bundled into the AndroidManifest.xml file. You can also specify additional members, such as required permissions for the service to operate. IntentFilter can also be applied as an attribute to filter what types of messages the service responds to. Apply the following attributes to the BackgroundService class:
Next, override the OnRunTask method, where we’ll define the logic to refresh the app data in the background automatically. You should return either GcmNetworkManager.ResultSuccess GcmNetworkManager.ResultReschedule or GcmNetworkManager.ResultFailed , depending on the result of the background operation:
GcmTaskService is a type of bound service, so we must create a class that subclasses the Binder class, as seen below:
The Binder class is responsible for maintaining a reference to our service so clients can make method calls against it. This is only created one time, in GcmTaskService ‘s OnBind method and remains until it’s unbound. Override the OnBind method and initialize and return the binder:
Schedule the Background Data Refresh
Now that the GcmTaskService is properly configured, it’s time to schedule our task using the GcmNetworkManager . We can use the PeriodicTask StartBackgroundDataRefreshService to your MainActivity and call it from the OnCreate lifecycle method:
Configuration & Testing
Finally, GcmNetworkManager requires a Google App Id to function properly, even if your app is not using Google Cloud Messaging services. To do this, create a new app in the Google Developers Console. Copy the application identifier and create a new string entry in the Strings.xml file in the Resources/values directory:
Run the app, and you’ll see it updates in the background every 30 seconds! For testing, ensure that the device (or emulator) in test has Google Play Services correctly installed, or GcmNetworkManager will not be able to properly operate.
Wrapping Up
In this blog post, we created a background data refresh service using the Google Cloud Messaging NuGet with GcmTaskService and scheduled our background service to run periodically using GcmNetworkManager . Adding background data refresh is super easy, and only requires a few lines of code to get up and running. For more information on background services, check out our documentation on Android services or our blog post on how to perform background refresh in iOS apps.
Pierce Boggan
Senior Program Manager, Mobile Developer Tools
Источник
How to turn off Background App Refresh on iPhone & Android to save phone data and battery
With all the things today’s smartphones are capable of doing, keeping your battery full throughout the day is easier said than done. But you may be surprised to learn that one of the biggest drains on your phone’s battery (not to mention your phone data) is a silent process that runs in the background, mostly without you knowing it: Background App Refresh.
Asurion Experts help customers 24/7 to get the most out of the tech, appliances and connections that they rely on—including discovering ways to extend the life of their phone battery. Here they share what you need to know about Background App Refresh, including how to turn it off on your iOS and Android devices.
What is Background App Refresh?
Background App Refresh allows the apps on your device to automatically search for new information even if they are not directly running on the screen. For example, your email app checking for new messages or your Facebook app updating your news feed, even if you aren’t actively using the app at the moment.
The good part? Background App Refresh keeps you from having to wait for new information to be fetched when you launch an app. The not so good? It can potentially keep your phone or tablet from performing at its best when it comes to battery life and data usage.
Does Background App Refresh use data?
Between email updates, text messages, videos and photos, you’re probably well aware of the fact that your smartphone burns through quite a bit of data every day.
However, what you may not know is that your smartphone could be burning through data for stuff you don’t need, like those apps and services that are constantly running and updating in the background without you knowing it. While one little app probably won’t use very much data, those little apps can add up to a serious drain on your data plan.
​Does Background App Refresh drain your battery?​
In addition to being a drain on your data plan, Background App Refresh can also have a negative impact on your phone’s battery life. While the feature can be useful, it’s not likely that you need up-to-date information on each and every installed app on your phone. Limiting the number of apps that you allow to use Background App Refresh will be beneficial to your phone’s battery life. Try turning it off on one of the apps that updates frequently (we’re looking at you, Facebook) and see if you experience any improvements.
If your battery life or data limits are a concern, luckily there’s a quick way to stop background apps.
Broken phone? We’re right around the corner
Head to the closest uBreakiFix by Asurion store for fast, affordable repairs.
How to turn off Background App Refresh on your iPhone and iPad
- Go toВ Settings.
- TapВ General.
- TapВ Background App Refresh.
- Turn off Background App Refresh completely by toggling it off – you also have the option to set it to refresh an app only while using Wi-Fi or while using Wi-Fi & Cellular Data.
How to turn off Background App Refresh on your Android
- From the start screen, pull down the notification bar forВ Settings.
- Tap the gear symbol in the top right-hand corner.
- In Settings, tapВ Connections, and thenВ tapВ Data Usage.
- From the Mobile section, tapВ Mobile Data Usage.
- Select an app from below the usage graph.
- TapВ Allow background data usage to turn off.
- Follow these steps for each app you would like toВ restrict from usingВ Background App Refresh.
How to turn off Background App Refresh for a specific app on your iPhone and iPad
If having up-to-date emails is a priority to you but knowing what’s happening on Twitter every moment is not, you can also choose to customize which apps do and don’t have Background App Refresh turned on based on your usage habits. Here’s how:
- Go toВ Settings.
- TapВ General.
- TapВ Background App Refresh.
- From the list of apps shown, use the toggle to turn Background App Refresh on or off for each app.
If you’ve turned off Background App Refresh and your battery is still draining quickly, chances are you may need a new battery. Stop by your nearest uBreakiFix by Asurion for a free phone diagnostic or help with any of your tech care needs.
Protect your phone
For more than 25 years, Asurion has helped 300 million customers protect, connect, and enjoy the tech they love most. And smartphones are no exception. Your life is on your device, make sure it’s protected. Learn more about Asurion phone insurance plans today.
*The AsurionВ® trademarks and logos are the property of Asurion, LLC. All rights reserved. All other trademarks are the property of their respective owners. Asurion is not affiliated with, sponsored by, or endorsed by any of the respective owners of the other trademarks appearing herein.*
Источник
Фоновое выполнение приложений в iOS 13
Главное событие года в мире iOS и MacOS-разработчиков, WWDC, неизменно радует всех занятых в индустрии людей выходом в свет новых версий операционной системы, фреймворков, железа — в общем, всего того, с чем собственно и предстоит работать.
Этот год исключением не стал и предметом активных обсуждений стали и новая версия iOS, и SwiftUI, и собственная ОС iPadOS для вы-сами-поняли-каких-устройств.
Однако были темы не столь освещенные, но от этого не менее интересные — например была затронута такая полезная вещь, как фоновое выполнение приложений.
Вкратце о теме
Для тех кто не совсем представляет, что такое фоновое выполнение (Background execution), поясним: выполнение в фоне означает выполнение приложением какой-либо работы в состоянии, когда физически на экране смартфона пользователя оно не запущено (т.е. не находится в foreground).
Данная картинка наглядно показывает, в каких состояниях приложение может пребывать и как попасть из одного в другое.
Также разработчики Apple в этой сессии сделали акцент на потреблении ресурсов (надеюсь, вполне очевидно, что при работе в фоне приложение продолжает потреблять энергию). Но пора перейти непосредственно к докладу.
Что было на WWDC
Собственно докладчики начали с того же, с чего и я — вкратце рассказали про работу в фоне и описали задачи, предполагающие свое выполнение там.
Двигаемся ближе к разработке. Есть 3 основных соображения Apple, когда речь заходит о фоновом исполнении:
- мощность
- производительность
- конфиденциальность
Все довольно просто — если задача приложения выполняется в фоновом режиме, это выполнение может происходить во время работы другого приложения на переднем плане (foreground). Таким образом, существует ограничение ресурсов, наложенное на вас, чтобы гарантировать, что ресурсы не будут чрезмерно потребляться. При превышении этих ограничений, ваше приложение может быть принудительно прекращено Apple, что приведет к замедлению дальнейшего времени запуска. По поводу конфиденциальности — компания настойчиво рекомендует разработчикам использовать все возможности их API для информирования пользователя о том, какие данные приложение использует в своей работе (даже в фоне).
Кстати список этих самых API выкатили довольно внушительный — обзор по ним отдельно делать не стали, но я советую обратить внимание в их сторону.
Да и на самой сессии на примере приложения-мессенджера разработчики Apple показали краткий обзор возможностей (видео с WWDC посмотреть стоит).
BackgroundTasks
Данному фреймворку посвящена чуть ли не половина доклада в этом году.
2 вида заданий, которые предоставляет эта новинка:
- App Refresh Task
- Background Processing Task
App Refresh Task
BG App Refresh Task — специальный тип фоновой задачи, который мы можем использовать для обновления данных приложения. Одна вещь, которая делает этот тип задачи очень особенным, — это поведение пользователя. iOS узнает, как часто и в какое время пользователь запускает ваше приложение, и пытается запустить BGAppRefreshTask в то время, когда пользователь вряд ли будет использовать приложение.
Да, дольше 30 секунд работать не получится — особенность весьма неприятная, оставшаяся с прошлых версий ОС.
Рассмотрим пример кода с просторов Интернета.
Есть несколько моментов, на которых надо остановиться и рассмотреть получше:
- Установите обработчик истечения срока действия на объект задачи (expirationHandler), так ка система предоставляет ограниченное время для завершения работы, и при его превышении, вам придется очистить ресурсы.
- Убедитесь, что метод setTaskCompleted был вызван, как только работа будет завершена.
- BGTaskScheduler — это основной класс, который использeуется для планирования фоновой работы.
Background Processing Task
Другим типом фоновых тасок является BG Processing Task. Вы можете использовать его для обучения модели ML на устройстве или сделать очистку в базе данных. Apple обещает, что на этот вид задач система способна выделять до нескольких минут времени, что является очень важным нововведением для тяжеловесных работ, не укладывающихся в жалкие 30 секунд.
- requiesExternalPower — логическое значение, указывающее, требуется ли для задачи обработки устройство, подключенное к источнику питания.
- requiresNetworkConnectivity — логическое значение, указывающее, требуется ли для задачи обработки подключение к сети.
Отладка
Здесь тоже не без приятностей. Задержка между запланированным временем выполнения фоновой задачи и моментом, когда система запускает приложение для ее выполнения, может составлять несколько часов. При разработке приложения можно использовать две частные функции для запуска задачи и принудительного ее досрочного завершения в соответствии с выбранной временной шкалой. Функции отладки работают только на устройствах.
Принудительное досрочное прекращение выполнения задания:
В заключение
BackgroundTasks — это отличный способ планирования вашей тяжелой работы с лучшим пользовательским опытом, используя условия среды. Учитывая то, что с 13-й версии системы многие методы для работы в фоне становятся устаревшими, фреймворк все равно будет пользоваться большой популярностью в приложениях. Учитывая вышеописанные возможности, это вполне логично.
Рекомендую также посмотреть видео с WWDC, описанные там примеры весьма интересны.
Источник