Android service background foreground

Работа с фоновыми задачами в Android 12: переезжаем с foreground service на expedited jobs

С релизом Android 12 приложения, где новая версия операционки будет указана в targetSdkVersion, получат запрет на запуск foreground-сервисов в бэкграунде. В качестве альтернативы Google предлагает WorkManager, который с появлением expedited jobs станет предпочтительным вариантом для запуска высокоприоритетных фоновых задач.

О нём и пойдёт речь в статье — под катом обсудим новые возможности инструмента, подключим его к приложению и реализуем миграцию с foreground-сервиса.

WorkManager и foreground service

Foreground service — это какой-либо сервис, о котором знает пользователь через нотификацию в статус-баре. Например, воспроизведение музыки или работа GPS в картах.

WorkManager — это API для планирования задач, которые будут выполняться, даже если выйти из приложения или перезагрузить устройство.

WorkManager уже давно является приоритетным способом выполнения длительных фоновых задач. К таким относятся синхронизация данных с бэкендом, отправка аналитики, периодическая проверка свободного места в системе с помощью PeriodicWork и так далее.

Но в WorkManager присутствовал и недостаток — не было никаких гарантий, что джоба начнётся незамедлительно после создания. В версии 2.3.0 разработчики добавили для воркеров метод setForegroundAsync(), который, по сути, превращал фоновую задачу в foreground-сервис и позволял немедленно приступить к её выполнению.

Такой подход ничем особо не отличался от разработки foreground-сервиса вручную, когда необходимо создавать объекты Notification и NotificationChannel при таргете выше, чем на Android Nougat.

Сейчас setForegroundAsync() объявлен устаревшим, а при попытке запустить сервис из бэкграунда на выходе будет ForegroundServiceStartNotAllowedException.

Expedited jobs

Этот тип джобов позволяет приложениям выполнять короткие и важные задачи, давая системе больше контроля над доступом к ресурсам. Он находится где-то между foreground-сервисами и привычными джобами WorkManager. От последних их отличает:

минимально отложенное время запуска;

обход ограничений Doze-mode на использование сети;

меньшая вероятность быть «убитыми» системой.

А ещё в них не поддерживаются ограничения по заряду батареи и режиму работы девайса:

У expedited job больший приоритет на ускоренный запуск, поэтому операционная система строже регулирует их количество. Например, если попытаться запланировать джобу при исчерпаном лимите, то сразу вернётся JobScheduler#RESULT_FAILURE.

Если же ограничения по квоте, сети и памяти устройства выполнены, то у джобы будет около минуты на выполнение своих функций. Иногда больше, но это сильно зависит от лимита и общей загруженности системы.

Миграция foreground service на expedited job

Стандартный сервис для выполнения фоновых задач обычно выглядит примерно так:

А запускается так:

Поговорим о том, как перевести этот сервис на expedited job. Происходит это буквально в три простых шага.

1. Подключаем WorkManager к проекту:

2. Создаём класс, наследующийся от Worker (он будет выполнять задачу, которую раньше делал сервис):

3. Создаём WorkRequest и передаём его для запуска в WorkManager:

Здесь есть важный параметр OutOfQuotaPolicy, который отвечает за поведение при невозможности запустить джобу немедленно. Он существует в двух вариантах:

RUN_AS_NON_EXPEDITED_WORK_REQUEST — при заполненной квоте запустится обычная джоба, не expedited.

DROP_WORK_REQUEST — при заполненной квоте запрос на выполнение сразу зафейлится.

На этом, собственно, базовая миграция заканчивается.

Вместо заключения

Переехать на expedited job довольно легко, особенно, если в проекте уже подключен WorkManager.

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

Источник

Android Services: Getting Started

Learn about Android Services and the differences between foreground, background and bound services.

Version

  • Kotlin 1.4, Android 5.0, Android Studio 4.2

Many Android apps have features that take a long time to run, like downloading content or updating a remote database. If developers don’t handle these features properly, they slowly clutter the main thread, creating memory leaks and inconsistencies in the results. This leads to a bad user experience.

Fortunately, there’s a solution for handling these actions: Android Services. This is a special type of application component that’s designed to handle repetitive and long running jobs.

In this tutorial, you’ll learn:

  • What Android Services are and how to declare them in the Manifest file.
  • How to use a foreground service while displaying a notification to the user.
  • What is it with background processing for complex work that isn’t related to the UI.
  • How to use a bound service.

Getting Started

Download the starter project by using the Download Materials button at the top or bottom of this tutorial.

For this tutorial, you’ll use the Memo app. Memo is a game that challenges the user to match cards in the shortest possible time. Additionally, the user can listen to audio tracks while they play.

The game has four levels: Beginner, Intermediate, Advanced and Expert. The higher the level, the more cards to match. After the user finishes the expert level, they complete the game. Do you dare to try your luck? :]

Currently, the app only lets the user start a game and manipulate the audio tracks. Once you start a game, you’ll be able to quit, preview game cards and track the time elapsed since the game started.

Open the project in Android Studio and get familiar with the files. When you’re done, build and run it on a device/emulator to see how the app looks.

Play the game by pressing PLAY BEGINNER LEVEL. At this point, you can match the cards but there’s no timer to show how long it took you to win. That’s the first thing you’ll implement in this tutorial.

First, however, you’ll take a deeper look at Android Services.

Introducing Android Services

An Android Service is a component that helps execute long-running processes, like updating a database or server, running a countdown and playing audio. By default, Android Services run in the same process as the main application thread does. This kind of service is also known as a local service.

For resource-intensive tasks, the service executes the work on the background thread. This lets the user run actions without being disturbed. For example, if the user wants to make a call or check messages while updating a server, they can do so without interrupting or aborting the update action.

Читайте также:  Android studio spinner background

To do this, the developer needs to create a background thread and manually specify which tasks should run on it because the service doesn’t directly support the thread implementation.

Since an Android Service doesn’t have a user interface, it isn’t bound to the activity’s lifecycle. That means you can run it even when the user isn’t interacting with the app.

Additionally, other components can bind to the service and interact with it, or even do InterProcess Communication (IPC). You’ll learn more about IPC later in this tutorial.

In the following sections, you’ll implement each of the below types of Android Services in the Memo app to achieve the following features:

  • Foreground service: Add TimerService , which contains logic to track time.
  • Bound service: Implement MusicService , which will let you play, pause, stop and shuffle the audio tracks.

It’s time to get started!

Declaring a Service in the Manifest

Before using a service, you need to declare it in AndroidManifest.xml. After all, it’s an Android component, just like Activities are. For simplicity, the starter project already contains the Service classes, but you still need to configure them properly.

Navigate to AndroidManifest.xml and add this code inside application :

In this code, you see the following:

  • android:name: The name of the Service class.
  • android:enabled: When set to true allows the system to instantiate the services.
  • android:exported: When set to false tells the system that components of another application can’t start these services.

The value of android:name is in red, but just ignore that for now. You’ll fix this soon.

For now, you’ll start with the implementation.

Implementing the Service Interface

Every custom service class must be a subclass of Service and must implement and override a few basic callback methods connected to the service lifecycle.

The most important of these are:

  • onStartCommand(): Called by the system when another component wants to start a service using startService() . Once the system calls onStartCommand() , the service can run in the background for as long as it takes to complete. You need to remember to stop the service manually when the work is over by calling stopSelf() or stopService() . You don’t need this implementation if you only want to bind to the service without an option to start it.
  • onBind(): You always need to implement this callback method. The system invokes it when bindService() is called. Use it to bind another component to the service. It opens a communication, so you’ll provide an interface for the clients to communicate by returning IBinder . If you don’t want to use binding, just return null .
  • onCreate(): Use this method to set up a service before it starts. The system invokes it only if the service isn’t running yet.
  • onDestroy(): The system invoke this to destroy the service when it is not needed anymore. It’s the last call the service receives and it cleans up the resources or threads.

Creating a Foreground Service

A foreground service executes tasks that the user needs to see. It shows a status bar notification to alert the user that an app is performing an operation and consuming resources. The notification must have a priority of PRIORITY_LOW or higher and must be visible even when the user isn’t interacting with the app.

The user can’t dismiss the notification; it disappears when the service stops or leaves the foreground.

To see this in play, you’ll implement TimerService . Open TimerService.kt and add the following to make it a subclass of Service :

With this code, you implement the Service and CoroutineScope interface.

Implementing the Service Methods

Look closely and notice that Android Studio is showing an error because onBind() is missing.

To fix this, add the following methods to TimerService :

Here is a breakdown of the code:

  1. Since this is a foreground service, you don’t need binding so you return null instead of IBinder . Also note that you won’t implement onCreate() now since you don’t need any specific setup for the service.
  2. Here, you go through the Intent extras to get the value that the key SERVICE_COMMAND saves. This value indicates which action the service should execute.
  3. If the system kills the service because the memory runs out, START_NOT_STICKY tells the system not to recreate the service with an undefined Intent . Alternative constants are START_STICKY and START_REDELIVER_INTENT . If you’re interested in these, check out the official service constants documentation.
  4. Remove all Handler callbacks for the ticking time to keep the memory clean. Also, clean up the resources by canceling the whole timer Job since you’ll destroy the service in the next step.

Adding Permissions

All apps that target Android 9 (API level 28) or higher must request permission to use a foreground service. The system automatically grants that request because it’s a type of normal permission. Failure to do so leads the app to throw a SecurityException.

In Project view, navigate to app ▸ manifest ▸ AndroidManifest.xml and add the following code above the application tag:

This lets you run the foreground service in Memo.

Next, you’ll create a notification for the service.

Creating a Notification Channel

Every foreground service must notify the user that it has started. You also need to define a Notification Manager, which notifies the user of events that happen and holds information about one or more notifications.

Open NotificationHelper.kt and add this code at the top of the class:

Here, you’re lazy initializing notificationManager by getting the NOTIFICATION_SERVICE system service and casting it as NotificationManager .

In Android 8 and later, the notification must be part of a notification channel. To create one, add this code to NotificationHelper.kt:

In this code, you:

  1. Create a notification channel with CHANNEL_ID as its ID, CHANNEL_NAME as its name and the default importance.
  2. Set the notification channel’s description to CHANNEL_DESCRIPTION and sound to null which just means that there is no sound played when a notification is triggered in the channel.

The next step is to define a notification view.

Creating a Notification Builder

For the user to be aware of the service running, create a view that the user can see in the status bar. At the top of NotificationHelper.kt, add the notification code:

If you get an error saying contentIntent isn’t defined, don’t worry. You’ll take care of it in the next steps.

For now, in this code:

  1. You’re using NotificationCompat.Builder to create a status bar notification builder.
  2. The builder has to contain information about some of the notification’s options. However, you don’t have to define the notification options when you declare a builder. If you’re missing information about the title, sound and so on, you can set that information later, in the notification itself.
  3. This kind of notification should be set as auto-cancelable, which means that when the user clicks it, it’s automatically dismissed.
Читайте также:  Радары для навигаторов андроид

Building a Notification

Now, it’s time to build the notification itself. Add the following to NotificationHelper.kt:

Here’s what’s happening above:

  1. If the version of Android is equal to or greater than Android 8, the system creates a notification channel and returns Notification . Unfortunately, the Support Library for versions before Android 8 doesn’t provide notification channel APIs. Read more about this issue in the official notification channel documentation.
  2. Return a Notification after invoking build() on the builder.

Notification can be dynamically updated. In this case, you’ll update the text if the user closes the app while the service is running.

Below getNotification() , add the following:

Here’s what’s happening:

  1. You update the text in the notification published in the status bar via the notificationBuilder
  2. Then notify the Notification Manager about which notification to update. To do that, you use a unique NOTIFICATION_ID .

Finally, you’ll define what happens when a user clicks on the notification. Add this to the top of NotificationHelper.kt:

Here, you’re doing a lazy initialization of PendingIntent , which launches MainActivity when the user presses the notification.

Great job! You’ve done a lot of work already. Now, it’s time to actually run the foreground service.

Starting and Stopping the Service

To start the service in the foreground, use startForeground() . This method needs two parameters: the unique positive integer ID of the notification and Notificaton .

Open TimerService.kt and add the below to startTimer() method:

This method makes the service run in the foreground and posts the notification with the ID of NOTIFICATION_ID to the status bar. You’ll notice that helper is highlighted in red because you haven’t defined that variable yet.

To fix that, create an instance of NotificationHelper class at the top of TimerService :

To try starting the service from another component, open MainActivity.kt, find sendCommandToForegroundService() and add:

Here, you start the service from Activity. You pass its Context and the Intent to start the service.

Everything that starts must end, and that includes Service . Open TimerService.kt and add the following to stopService() :

In this code block:

  1. This call tells the system that it should remove this service from foreground state. The passed boolean argument corresponds to removing the notification when set to true
  2. Since a service can start itself, it must handle stopping itself, as well. stopSelf() handles that use case.

Updating the Notification When the Timer Changes

TimerService contains a coroutine that ticks every second while the level is running. You’ll use the timer value to update the notification view.

Look for broadcastUpdate() inside the TimerService.kt, and add this code inside the if :

Here is what this code block does:

  1. Here, you send a broadcast with the elapsed time to MainActivity . With it, MainActivity can update the time in the TextView below the card’s view.
  2. This helper method updates the status bar notification you posted above.

At this point, you’ve implemented everything the user sees while playing the game. But what happens if the user kills the app while the timer is running?

To handle that, add the following line to broadcastUpdate() in the else if :

This line updates the notification text to call the user back to the game.

Awesome work! Build and run to test the timer. Start a level and notice how the timer changes at the bottom. Pull down the status bar to see how the timer changes within the notification. Try exiting the application to test the message text update in the notification.

Using Background Processing for Complex Work

Sometimes, the user doesn’t need to know about certain actions happening, e.g. if you store the user’s activity on the server for developing purposes, you don’t have to display a notification. Place this kind of continuous work and similar in the background.

To achieve that, you can use:

  1. Custom Background Service – by default, the service runs on the UI thread. To avoid blocking it, create a Service with a job processing on the background thread.
  2. IntentService – a subclass of Service that executes requests sequentially by using worker thread. Since Android 8, it’s usage is not recommended. Also, IntentService is deprecated from Android 11.
  3. JobIntentService – a replacement for IntentService. Instead of service, it uses JobScheduler for executing jobs. In earlier versions than Android 8, it will act just like IntentService. For more info, read the official JobIntentService documentation.
  4. Background work with WorkManager – this is a general concept for doing background work in Android. Use it when you want to execute a periodical job in the future, or when you have some job constraints.

Explaining Background Execution Limits

Android 8 and newer versions have restrictions when using Android Services on the background thread:

  1. The system will destroy the service after some time if the app runs the service in the background. Once it goes to the background, it has a window of a few minutes in which it can interact with services. After that, the system kills all running services.
  2. The system will throw an exception if the service was started when the app is in the background and outside of the time window.

Now, it’s time to learn about the last kind of service.

Creating a Bound Service

A bound service is an implementation of Service . It’s a component that other components bind to, interacting with it and performing interprocess communication (IPC). The bound component can be an Activity, another service, a broadcast receiver or a content provider.

The lifecycle of the bound service depends on another application component. When the component unbinds, the bound service destroys itself. Consequently, it can’t run in the background forever.

However, it doesn’t necessarily need a bound component — it can start and stop itself as well. In that case, there’s an option to run indefinitely.

To try this out, you’ll give Memo the ability to play audio.

Converting MusicService into actual Service

To implement the audio playing feature, you’ll use MusicService . Firstly, modify it to have access to basic service methods.

Open MusicService.kt and make it extend Service :

As its type says, another component will use this service to bind to it. You already learned about the mandatory method you need for binding to service, so add it to MusicService :

The difference between the last implementation of onBind() and this one is, obviously, the return value. Since you’re binding to service here, you need to provide the IBinder value.

Читайте также:  Защита конфиденциальности для android

IBinder is a programming interface of Binder that clients use to interact with the service. Its methods allow you to send a call to an IBinder object and receive a call coming in to a Binder object. To learn more, check out IBinder’s documentation.

Android Studio shows an error because you haven’t defined binder variable. To fix this, add the following to the top of the class:

Here, you’re doing a lazy initialization of binder , which is a type of MusicBinder . Implementation of MusicBinder is your next step.

Defining a Binder

This service can’t be accessed outside of this application and doesn’t have its own process. Therefore, you have to create an interface that will have access to the service’s context. Do that by extending the Binder class. This way all components can use all public methods from Binder or the Service.

Now, to define the interface, add these lines at the bottom of the class:

MusicBinder is nested inside another class and it can access all methods from it. It can use all of Binder’s methods as well. Inside of it, you create a method for retrieving a service context.

Defining Service Methods for Managing Audio

This service allows the user to interact with the audio icons for playing, pausing, stopping and shuffling the music. For simplicity, the methods for managing audio are already defined. However, a music player isn’t.

To instantiate the music player, use this code inside initializeMediaPlayer() inside MusicService.kt:

Here, you use MediaPlayer to run a continuously repeating audio of the first song in randomSongs .

Another fun feature is that this bound service can provide the name of the track that’s playing. Inside MusicService , add:

In this method, you’re reading a track name from the resources and changing the result String to be more readable to the user.

All done! Now, you’ll use these methods from another component.

Creating a Service Connection Callback

To use MusicService inside other classes, you have to create its instance. Open MainActivity.kt and add the following at the top of the class:

Here, you’re declaring a service variable that holds a service instance. For now, the service is null. You’ll assign a new value when the activity connects to the service by using the Binder interface. To catch the connection state changes, create a connection callback.

Add the code below the musicService initialization:

That code is easy to digest:

  1. This is a callback for the service connection state.
  2. When activity connects to service, the system uses MusicBinder instance and getService() to give a reference to musicService .
  3. When service disconnects, the audio will stop if the service reference isn’t already null , clearing the service reference.

This sets a flag, isMusicServiceBound , that checks a service-bound state in both methods according to the parameter you provided. This is important to avoid DeadObjectException exceptions, which remote methods throw when the connection breaks.

Binding to the Service

Your next step is to bind the service when MainActivity starts. Find onStart() and add:

Here, you’re checking whether the service has a binding already. If not, you call a binding method.

The binding method doesn’t exist yet, so add its code below onDestroy() :

In this code, you:

  1. Declare an intent to start MusicService .
  2. Provide the Intent to the service along with the connection callback and a flag that automatically creates the service if the binding exists.

To avoid memory leaks or bugs, you need to add code to unbind the service. Add the following to unbindMusicService() :

With this, you tell the service to execute onServiceDisconnected() in the boundServiceConnection callback.

Using Service Methods

Once the service unbindes, you need to stop the music. Add the following code above the unbindService() line you just added:

Here, you use the service instance to stop the audio. Remember that you weren’t able to call methods from TimerService . Then, you needed to provide flags through Intent . However, here you have a connection — a binding — to the service, so you’re able to call its methods and receive a response.

To trigger an audio action, use sendCommandToBoundService() . Now, create a generic call for changing the action to reduce a number of code lines. Add this line to sendCommandToBoundService() :

With this, you tell the service to execute an action that matches the sendCommandToBoundService() parameter.

There is one more thing to do! Once the song starts to play, the service can provide info about the song’s name. Before you try that out, you need to fix the part with receiving a result.

Inside getNameOfSong() , replace the line which returns “Unknown” text with:

Here, you call a method from the service that checks which audio track is currently playing and returns an optional String result. If the result is null , you use a resource text instead.

Build and run, then press the Play icon to start the audio. Press GET SONG NAME to see the running song name in a Toast message. Finally, you can enjoy sound while playing your game!

Interprocess Communication

Every Android app runs in its own process with a unique process ID. When you start an app, the Android system generates a process and runs a main activity on the main thread. This has the advantage that the app lives in an isolated environment and other apps can’t interrupt it.

Based on this, Android allows you to run components in a different process that isn’t used to start an app. To do this, you need to use the process tag inside AndroidManifest.xml. The process can have a random name, like myNewProcess.

Multiprocessing gives your app better security and memory management. If you use it, however, you need to find a way to communicate between different processes.

You only need to include one programming interface — IBinder — but Android provides three ways of defining it:

You already implemented the first approach in this tutorial, but feel free to investigate the other two.

Where to Go From Here?

Download the final project using the Download Materials button at the top or bottom of this tutorial.

You’ve learned a lot of new things about Android Services and how to implement them in different ways. Services are useful for app optimization and improving the user experience.

Here are some links you can refer to:

Android 12 will bring some changes to foreground notifications. Check them out in the official foreground services documentation.

If you have any questions or comments, feel free to join the forum discussion below.

Источник

Оцените статью