background app refresh что это

Фоновое выполнение приложений в iOS 13

Главное событие года в мире iOS и MacOS-разработчиков, WWDC, неизменно радует всех занятых в индустрии людей выходом в свет новых версий операционной системы, фреймворков, железа — в общем, всего того, с чем собственно и предстоит работать.

Этот год исключением не стал и предметом активных обсуждений стали и новая версия iOS, и SwiftUI, и собственная ОС iPadOS для вы-сами-поняли-каких-устройств.

Однако были темы не столь освещенные, но от этого не менее интересные — например была затронута такая полезная вещь, как фоновое выполнение приложений.

Вкратце о теме

Для тех кто не совсем представляет, что такое фоновое выполнение (Background execution), поясним: выполнение в фоне означает выполнение приложением какой-либо работы в состоянии, когда физически на экране смартфона пользователя оно не запущено (т.е. не находится в foreground).

Данная картинка наглядно показывает, в каких состояниях приложение может пребывать и как попасть из одного в другое.

Также разработчики Apple в этой сессии сделали акцент на потреблении ресурсов (надеюсь, вполне очевидно, что при работе в фоне приложение продолжает потреблять энергию). Но пора перейти непосредственно к докладу.

Что было на WWDC

Собственно докладчики начали с того же, с чего и я — вкратце рассказали про работу в фоне и описали задачи, предполагающие свое выполнение там.

Двигаемся ближе к разработке. Есть 3 основных соображения Apple, когда речь заходит о фоновом исполнении:

Кстати список этих самых API выкатили довольно внушительный — обзор по ним отдельно делать не стали, но я советую обратить внимание в их сторону.

Да и на самой сессии на примере приложения-мессенджера разработчики Apple показали краткий обзор возможностей (видео с WWDC посмотреть стоит).

BackgroundTasks

Данному фреймворку посвящена чуть ли не половина доклада в этом году.

2 вида заданий, которые предоставляет эта новинка:

App Refresh Task

BG App Refresh Task — специальный тип фоновой задачи, который мы можем использовать для обновления данных приложения. Одна вещь, которая делает этот тип задачи очень особенным, — это поведение пользователя. iOS узнает, как часто и в какое время пользователь запускает ваше приложение, и пытается запустить BGAppRefreshTask в то время, когда пользователь вряд ли будет использовать приложение.

Да, дольше 30 секунд работать не получится — особенность весьма неприятная, оставшаяся с прошлых версий ОС.

Рассмотрим пример кода с просторов Интернета.

Есть несколько моментов, на которых надо остановиться и рассмотреть получше:

Background Processing Task

Другим типом фоновых тасок является BG Processing Task. Вы можете использовать его для обучения модели ML на устройстве или сделать очистку в базе данных. Apple обещает, что на этот вид задач система способна выделять до нескольких минут времени, что является очень важным нововведением для тяжеловесных работ, не укладывающихся в жалкие 30 секунд.

Отладка

Здесь тоже не без приятностей. Задержка между запланированным временем выполнения фоновой задачи и моментом, когда система запускает приложение для ее выполнения, может составлять несколько часов. При разработке приложения можно использовать две частные функции для запуска задачи и принудительного ее досрочного завершения в соответствии с выбранной временной шкалой. Функции отладки работают только на устройствах.

В заключение

BackgroundTasks — это отличный способ планирования вашей тяжелой работы с лучшим пользовательским опытом, используя условия среды. Учитывая то, что с 13-й версии системы многие методы для работы в фоне становятся устаревшими, фреймворк все равно будет пользоваться большой популярностью в приложениях. Учитывая вышеописанные возможности, это вполне логично.

Рекомендую также посмотреть видео с WWDC, описанные там примеры весьма интересны.

Источник

What Is Back­ground App Refresh on iPhone and iPad

Mehvish

27 Jan 2021

Turning off Background app refresh on your iPhone or iPad is a great tip to improve battery. But you might be apprehensive about what happens by turning off Background app refresh. In this post, we shall tell you what is meant by Background app refresh in iPhone and iPad Settings and whether you should keep it enabled or not.

Читайте также:  какой коньяк лучше 3 или 5 звездочный

Apple introduced Background app refresh with iOS 7, and since then, it continues to be part of every iOS update. By the end of the post, you will know about the benefits of Background app refresh and how to enable or disable it.

What Is Background App Refresh in iPhone and iPad Settings

To understand the Background app refresh feature in iOS and iPadOS, you will need to know about an app’s life cycle. Keeping it simple, when you are using an app, it is said to be active and in the foreground. When you press the Home button or open a new app, the first app goes in the background. You can still access it from the multitasking or the app switcher (recent apps) screen, where it is said to be in a suspended state after a short period of time.

Now, this is where the Background app refresh comes into the picture. With Background app refresh enabled, the apps in suspended mode can check for new content regularly. So if you switch to a suspended app present in the app switcher screen, you will be greeted by the new data without waiting or refreshing.

However, if you quit or close the app from the app switcher, enabling Background app refresh doesn’t do much. The app’s content will then update only when you open the app. Basically, Apple smartly understands user behavior over time and stops refreshing content in the background.

For instance, if you don’t open Facebook or Instagram app for several days, you will not see the latest posts immediately when you open it later since it was inactive or not in the running stage. The app will take its time to refresh and show the latest posts.

So with Background app refresh, suspended apps update the content periodically in the background so that new content is available to you.

Источник

Background App Refresh Explained

You’ve probably seen a lot of articles telling you to turn off background app refresh because it saves you a lot of battery. There’s a lot of confusion about whether you should turn this on or off so this article is going to show what this feature does and why many people think that turning it off is going to save you battery life.

Life Cycle of an App

A life cycle of an app is basically the stages an app goes through on your iPhone and iPad.

On your iPhone and iPad right now, you have apps that you use a lot and apps that you hardly use. Every app on your iOS device is in a specific stage right now. Whether you’ve never opened the app, or you’re using the app right now to read this article, that app is in a current state.

When you’re performing actions on a certain app such as opening it and then leaving it in the background, this app is moving from state to state as you perform certain actions to it. For example, you open the Phone app and close it, then a call comes in – this app is moving from state to state as it is moving from one action to the other.

Here’s an explanation of all the states an app on your device is in right now explain in the Apple Documentation.

State Description
Not running The app has not been launched or was running but was terminated by the system.
Inactive The app is running in the foreground but is currently not receiving events. (It may be executing other code though.)

An app usually stays in this state only briefly as it transitions to a different state.

Active The app is running in the foreground and is receiving events.

This is the normal mode for foreground apps.

Background The app is in the background and executing code.

Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time.

Suspended The app is in the background but is not executing code.

The system moves apps to this state automatically and does not notify them before doing so.

While suspended, an app remains in memory but does not execute any code.

Here’s an image from Apple’s documentation which shows the life cycle of an app from one state to the next.

What is Background App Refresh?

Background app refresh is a feature on your iPhone that allows apps to refresh their content in the background. This allows your app to check for new information while it’s in the background.

The apps are only allowed to be checked for new content at certain times and not at random. This can also happen when your battery is at a certain level and in a certain location.

For example, you’re scrolling through your Instagram feed and you decide to leave the app for a few minutes and get back to the work you were doing. If background app refresh is turned on, the content on Instagram is going to be refreshed at a certain time in the background.

This is because you’ve given your iPhone permission for Instagram to look for new content in a suspended state.

How Does Background App Refresh Work?

When you’ve left an app in the background, it’s then left for a while until the app is put into a suspended state. This means that the app is not in use anymore and when you open it again, they’ll already be open because it was never closed.

App refresh doesn’t give the apps in the background permission to run content checks whenever it wants. If background app refresh is on, the apps check for content in an intelligent and efficient way that limits the battery your iPhone or iPad is using.

To limit the usage of your iPhone battery, background app refresh only happens at certain times which maximins the efficiency of how the feature affects your iPhone. If you’re connected to WI-FI and app refresh is turned on, this is a queue for it to refresh after a certain time.

When you start to charge your iPhone or iPad, this is also a queue for your apps to refresh in the background. So, if none of these situations is occurring and you’re not using your phone much, background app refresh isn’t going to take place.

Does Turning off Background App Refresh Save Battery?

Since background app refresh is turned on, your apps are going to check for content by itself, therefore, this causes your iOS device to ‘work’. When your phone is working, this means that your iPhone battery drains.

Although the battery drained is very negligible, the battery is still drained. This is why you see a lot of battery saving articles telling you to turn off background app refresh. They are right because it does save your battery.

How to Turn off Background App Refresh

1. Go to settings

2. Tap on General

3. Scroll down and tap on background app refresh

4. Toggle Background App Refresh off

In very simple terms, Background App Refresh allows apps to check for new content while the apps are in the background and it then updates the app (content wise) while you aren’t using them. When you go back onto the app, you’ll see the new content that it found while the app was in the background e.g Facebook will update the feed while it’s in the background.

Источник

Функция фонового обновления iOS 7 в 16 раз увеличила трафик погодного приложения

В операционной системе iOS 7 компания Apple впервые представила функцию фонового обновления приложений. Разработчики, решившие воспользоваться данным новшеством, жалуются на то, что «яблочные» смартфоны и планшеты создают серьезную нагрузку на их серверы.

Функция Background App Refresh или Background Fetch предусматривает возможность загрузки контента в приложения в фоновом режиме. Данные поступают с определенной периодичностью – разработчики могут самостоятельно настраивать частоту обновления. У пользователей iPhone и iPad, в свою очередь, есть возможность разрешить или запретить фоновую загрузку данных для любой программы из меню Настройки –> Основные –> Обновление контента.

Разработчик из компании Pod Wrangler Дэвид Смит пожаловался на то, что после включения функции фонового обновления для его погодного приложения количество запросов к серверу выросло почти в 16 раз.

«Я решил воспользоваться функцией Background Fetch, чтобы загружать данные в программу в фоновом режиме. Назначение моего приложения – демонстрация прогноза погоды в реальном времени, поэтому я решил установить самую большую частоту запросов. Результат оказался хуже, чем я мог предполагать. На графике видно, насколько сильно увеличилось число запросов к API (стоимость каждого 0,01 цента). Трафик вырос до невероятных размеров – почти в 16 раз. Мне пришлось в срочном порядке выпускать обновление, чтобы уменьшить частоту обращения к серверу», – рассказал разработчик.

С подобной проблемой столкнулись также создатели подкаст-клиентов и других приложений, которые регулярно загружают данные из Сети.

Между тем функция фонового обновления данных в iOS 7 «вредит» не только создателям ПО, но и владельцам iPhone и iPad. Background App Refresh серьезно расходует заряд батареи мобильного устройства. Как мы рассказывали в статье «30 советов, как увеличить время автономной работы в iOS 7», один из способов увеличить автономность гаджетов – отключить использование сервисов в фоновом режиме.

Источник

How to manage Background App Refresh on iPhone and iPad

Background refresh is part of what allows any app for iPhone or iPad to appear to be multitasking all the time. The truth is, they’re really multitasking «just in time» by updating in the background whenever they have the opportunity — or right before they figure you’ll be launching them.

In spite of how efficient Apple has tried to make background refresh, some apps still manage to consumer a ton of power and resources. Yes, looking at Facebook so hard. Luckily, if either your battery life or your data limit is a concern, you can turn off background refresh all together — or just for those apps you don’t consider that important.

Shop Cyber Monday deals at: Amazon | Walmart | Best Buy | Apple | Dell

How to turn off Background App Refresh on iPhone or iPad

Tap on General.

Toggle Background App Refresh to off. The switch will become grayed-out when toggled off.

How to turn off Background App Refresh for individual apps on iPhone and iPad

The master switch handles Background App Refresh for all apps at the same time. But what if you want to turn it off for some apps only? You can do that by toggling off the switches for each individual app. Here’s how to do that/

Tap on General.

Toggle Background App Refresh switch to the right of the app for which you wish to disable it to off. The switch will become grayed-out when toggled off.

That’s it for Background App Refresh. If you ever want to turn it back on, simply go back and toggle the switches to on.

Источник

Читайте также:  с каким предлогом употребляется arrive
Сказочный портал