What is android service manager

Наша Service и опасна и трудна или некоторые аспекты выживания служб в Android

Вместо введения

Во многих практических задачах требуется выполнение различных фоновых действий, будь то проигрывание музыки, обмен данными с сервером или просто слежение за действиями пользователя дабы похитить у него реквизиты кредитных карт. Ну а если не получится, то по крайней мере завалить его целевой рекламой, используя полученные сведения. Как уже давным-давно все знают, в Android такие вещи оформляются в виде службы (Service).

Официальная документация гласит, что ОС Android останавливает службу только в случае нехватки памяти. Тем не менее, существует и другие случаи. Пользователь может сам остановить службу, используя предоставляемые ему средства меню Settings/Apps, там же он может сделать и полную остановку приложения. Но для этого ему надо напрягаться и, в общем-то осознавать свои действия и их последствия. К сожалению, для уничтожения службы у него есть и другие возможности, которыми он может пользоваться бессознательно. В частности, если в нашем приложении ранее была запущена хоть одна Activity, видимая в истории, то пользователь буквально одним движением пальца сможет вынести соответствующую задачу. Как ни парадоксально, попутно Android вышибет и весь процесс вместе со службой.

Лично мне такое поведение Android логичным не кажется. Пользователь зачастую просто чистит Recent Apps от давно забытого хлама, совсем не обязательно он при этом желает отказаться от тех благ, которые ему предоставляла выполняющаяся служба. Однако разработчики Google мыслили немного по-другому. По-другому, так по-другому, их право, но в конце концов нам с вами тоже надо как-то жить.

Итак, каркас простейшего приложения для отработки приемов борьбы.

Здесь все элементарно. SomeActivity при создании запускает службу KamikadzeService, которая, в свою очередь, стартует, как липкая или sticky. Для агентов враждебных платформ поясню, что служба при старте дает указание операционной системе в случае непредвиденного завершения сервиса перезапустить его при первой возможности. Делает она это, возвращая START_STICKY из метода onStartCommand. Если служба не липкая, то после удаления пользователем задачи шансов на возрождение после смерти у нее не будет.

Метод onTaskRemoved вызывается системой как раз при удалении пользователем задачи. Здесь совершенно необходимо упомянуть об атрибуте службы android:stopWithTask, который можно выставить в манифесте. Как можно догадаться по его названию (либо просто почитав документацию), если android:stopWithTask = ”true”, то волевое движение пальца пользователя по нужному квадратику в Recent Tasks List наряду с удалением задачи будет и останавливать службу. Поскольку в этом случае сервис будет считаться согласным на остановку, то и перезапускать автоматически никто ничего не будет — умерла, так умерла.

В самом начале моей борьбы за относительную устойчивость сервисов, обнаружив наличие этого флага, я имел наивность предположить, что проблема решится установкой android:stopWithTask = ”false” и сервис больше не будет умирать вместе с задачей. Увы, действительность и мечтания имели ряд существенных отличий. Действительно, в этом случае система не будет останавливать службу. Она ее просто прибьет без соответствующего предупреждения. Кстати, по умолчанию этот атрибут равен ”false”, из чего уже можно было догадаться, что явная его установка ни к чему не приведет

Для столь же простодушных разработчиков подытожу: значение атрибута службы android:stopWithTask никак не влияет на ее шансы остаться в живых после удаления задачи пользователем, служба в любом случае обречена. Этот атрибут всего лишь определяет, какой метод сервис будет вызван перед уничтожением. Если он равен ”true”, то у службы будет вызван метод onDestroy (не во всех, мягко говоря, случаях, но об этом чуть позже). А если атрибут равен ”false”, то последним вздохом сервиса, заметным разработчику, будет запуск метода onTaskRemoved.

Изучив все это и всласть поэкспериментировав с приведенной программкой, можно сделать следующий вывод: у нас не получится избежать гибели background service при удалении задачи. Ну не получится и не получится, в конце концов легкой жизни никто не обещал. Раз уж система может перезапускать нашу липкую службу, пусть делает это. А мы просто будем время от времени сохранять ее состояние, восстанавливая его при возрождении службы из пепла. Увы, не все так просто.

KitKat. No rest for the wicked

Еще в СССР в конце 80-х в рамках цикла передач “Сколько-то там вечеров с Thames Television” показывали рекламу шоколада KitKat. Ни про какой KitKat никто в то время не слыхивал, но реклама была в новинку и просматривали ее с интересом. И я отлично запомнил слоган, который сейчас и воткнул в название раздела. Ибо отражает.

Читайте также:  Год выпуска первых андроид

В качестве предисловия. Выше упоминалось, что при android:stopWithTask=”true” сервис именно останавливается, то есть перед смертью получает свой успокоительный onDestroy. Так было до появления Android KitKat, с приходом которого все неуловимо изменилось. При удалении пользователем задачи в этой и более поздних версиях Android служба перейдет в иной мир … бесследно. В подавляющем большинстве случаев. Если конечно, не считать возможный вызов onDestroy у Activity, попавшему пользователю под палец. Очевидно, что все это делает android:stopWithTask совершенно бесполезным для наших целей.

Но выпуск Android KitKat хорошо запомнился разработчикам фоновых служб совсем не поэтому. Дело в том, что в первоначальных вариантах этой версии крылась одна занимательная деталь, которая в свое время лично меня вогнала в состояние глубокой депрессии. KitKat никогда не перезапускал sticky-сервисы.

А дальше были крики душ программистов на stackoverflow, ворох тикетов в Google, исправления, обновления и т.д. Сколько таких прошивок до сих пор живы на устройствах, никто не знает. Но то, что они еще попадаются, это точно. Решение в лоб с попыткой перезапустить службу

не дает ничего, поскольку Android сначала отработает старт, а лишь потом со спокойной совестью уничтожит службу. Здесь придется добавить костыль в виде AlarmManager:

То есть планируем перезапуск службы вручную через три секунды после удаления задачи. Время взято с потолка.

Передний край нащупала разведка

Тот, кто читал эту статью сначала, помнит мое утверждение о неотвратимости смерти background service при удалении задачи. Признаюсь, я здесь немного манипулировал терминами. На самом деле у службы существует способ остаться целой и невредимой, но уже в виде foreground service. Например, так:

При создании служба создает уведомление, в нашем случае это всего лишь иконка приложения. Созданное уведомление передается в метод startForeground и — вуаля — служба становится почти бессмертной. Удаление задачи на нее никак не повлияет, да и при нехватке памяти она будет останавливаться только в самом крайнем случае. Практически единственный способ ее остановить — нажимание соответствующих кнопок в Settings/Apps, что, в общем-то и требовалось. Так зачем же я городил огород до этого? А дело в этом самом уведомлении, которое Google с давних пор требует для перевода службы на передний план. Оно заметно для пользователя, заметно даже если его создать с прозрачной иконкой. А для ряда приложений это не всегда хорошо. Я сейчас говорю не о троянах и прочих вредоносных программах, их создатели вряд ли озабочены описываемой проблемой вообще, поскольку по определению не должны показывать пользователю что-то, за что он может потянуть. Просто показ уведомлений, не обусловленных реальной необходимостью, выглядит, на мой взгляд, глуповато. Пользователь это также чувствует и зачастую это его даже раздражает, как видно из комментариев к некоторым приложениям в Google Play.

Но и против уведомлений у нас нашлись методы, правда это уже не костыль, а скорее, хак. Добавим еще одну службу в проект:

А onCreate в KamikadzeService перепишем так:

Суть подхода в том, что служба HideNotificationService, выйдя не передний план с тем же идентификатором 777, уходит опять на задний с удалением своего уведомления. Заодно уничтожается и уведомление KamikadzeService, но последняя остается на переднем плане, причем уже «на первый взгляд, как будто, не видна». После этого служба HideNotificationService прекращает работу. Следует уточнить, что порядок запуска служб, как и их выхода на передний план здесь не имеет значения, главное обеспечить, чтобы stopForeground второй (HideNotificationService) был вызван позже, чем startForeground первой (KamikadzeService). И обязательно равенство идентификаторов, передаваемых в startForeground.

И здесь опять возникает резонный вопрос — если все это прекрасно работает, зачем я ранее долго и нудно разжевывал про повадки ”чисто” фоновых служб? Да потому что описанный прием — хак и хак достаточно грязный, чтобы им еще долго можно было пользоваться. Хотя в эмуляторе с прилетевшим на днях Android 6.0 это пока работает. Надеяться или не надеяться — решать читателю.

Источник

Android Services — Tutorial

Using styles and themes in Android. Developing own services and using system services in Android. This tutorial describes how to create and consume Android services.

1. Android Services

1.1. What are services?

A service is a component which runs in the background without direct interaction with the user. As the service has no user interface, it is not bound to the lifecycle of an activity.

Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.

Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them. Services can also be configured to be restarted if they get terminated by the Android system once sufficient system resources are available again.

It is possible to assign services the same priority as foreground activities. In this case it is required to have a visible notification active for the related service. It is frequently used for services which play videos or music.

Читайте также:  Continue on pc android ios windows

1.2. Services and background processing

By default, a service runs in the same process as the main thread of the application.

Therefore, you need to use asynchronous processing in the service to perform resource intensive tasks in the background. A commonly used pattern for a service implementation is to create and run a new Thread in the service to perform the processing in the background and then to terminate the service once it has finished the processing.

Services which run in the process of the application are sometimes called local services .

1.3. Platform service and custom services

The Android platform provides and runs predefined system services and every Android application can use them, given the right permissions. These system services are usually exposed via a specific Manager class. Access to them can be gained via the getSystemService() method. The Context class defines several constants for accessing these services.

An Android application can, in addition to consuming the existing Android platform services, define and use new services. Defining your custom services allows you to design responsive applications. You can fetch the application data via it and once the application is started by the user, it can present fresh data to the user.

1.4. Starting and defining custom services

Custom services are started from other Android components, i.e., activities, broadcast receivers and other services.

1.5. Foreground services

A foreground service is a service that should have the same priority as an active activity and therefore should not be killed by the Android system, even if the system is low on memory. A foreground service must provide a notification for the status bar, which is placed under the «Ongoing» heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

2. Defining custom services

2.1. Implementation and declaration

A service needs to be declared in the AndroidManifest.xml file and the implementing class must extend the Service class or one of its subclasses.

The following code shows an example for a service declaration and its implementation.

2.2. Start a service

An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method.

Alternatively, you can also start a service via the bindService() method call. This allows you to communicate directly with the service. We discuss that later.

2.3. Service start process and execution

If the startService(intent) method is called and the service is not yet running, the service object is created and the onCreate() method of the service is called.

Once the service is started, the onStartCommand(intent) method in the service is called. It passes in the Intent object from the startService(intent) call.

If startService(intent) is called while the service is running, its onStartCommand() is also called. Therefore your service needs to be prepared that onStartCommand() can be called several times.

What if you call this method twice in your code? Do you have to worry about synchronizing the onStartCommand() method call? No, this method is called by the Android system in the main user interface thread, therefore it cannot be called simultaneously from two different threads.

A service is only started once, no matter how often you call the startService() method.

2.4. Service restart behavior

In its onStartCommand() method call, the service returns an int which defines its restart behavior in case the service gets terminated by the Android platform. You can use the constants, the most common options are described by the following table.

Table 1. Restart options

Service is restarted if it gets terminated. Intent data passed to the onStartCommand method is null. Used for services which manages their own state and do not depend on the Intent data.

Service is not restarted. Used for services which are periodically triggered anyway. The service is only restarted if the runtime has pending startService() calls since the service termination.

Similar to Service.START_STICKY but the original Intent is re-delivered to the onStartCommand method.

Option Description
You can check if the service was restarted via the Intent.getFlags() method. START_FLAG_REDELIVERY (in case the service was started with Service.START_REDELIVER_INTENT) or START_FLAG_RETRY (in case the service was started with Service.START_STICKY) is passed.

2.5. Stopping a service

You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service.

A service can terminate itself by calling the stopSelf() method. This is typically done if the service finishes its work.

3. IntentServices for one time tasks

You can also extend the IntentService class for your service implementation.

The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminates itself automatically. An example for its usage would be downloading certain resources from the internet.

The IntentService class offers the onHandleIntent() method which will be asynchronously called by the Android system.

4. Communication with services

4.1. Options for communication

There are several possibilities for a communication between an activity and a service. The following description discusses the possible approaches and provides recommendation which to use.

4.2. Using Intent data

In a simple scenario no direct communication is required. The service receives the intent data from the starting Android component and performs its work. No notification is necessary. For example, in case the service updates a content provider, the activity is notified by the content provider and no extra step in the service is necessary. This approach works for local and services running in their own process.

4.3. Using receiver

You can use broadcasts and registered receivers for the communication. For example, your activity can register a broadcast receiver for an event and the service sends outs corresponding events. This is a very typical scenario, in which the service need to signal to the activity that his processing has finished.

This communication flow is depicted in the following graphic.

This approach works for local and services running in their own process.

Android provides the LocalBroadcastManager class in the support library v4. This is a helper class to register for and send broadcasts of Intents to local objects within your process. This approach improves security as the broadcast events are only visible within your process and is faster than using standard events.

4.4. Activity binding to local service

If the service is started in the same process as the activity, the activity can directly bind to the service. This is a relatively simple and efficient way to communicate and recommended for activities which need to have a fast communication layer with the service.

This approach works for local services.

4.5. Handler and ResultReceiver or Messenger

If the service should be communicating back to the activity, it can receive an object of type Messenger via the Intent data it receives from the activity. If the Messenger is bound to a Handler in the activity, the service can send objects of type Message to the activity.

A Messenger is parcelable, which means it can be passed to another process and you can use this object to send Messages to the Handler in the activity.

Messenger also provides the method getBinder() which allows passing a Messenger to the activity. The activity can therefore send Messages to the service.

This approach works for local services running in their own process.

4.6. AIDL for services in a different process

To bind to a service which runs in a different process, you need to use Inter Process Communication (IPC) to community your the data. To do so, you need to create a AIDL file which looks similar to a Java interface, but ends with the .aidl file extension and is only allowed to extend other AIDL files.

This approach is required if you need to bind to a service running in another process, i.e., if your service is consumed by other Android applications.

You can find more information about this approach in the Android developer documentation about AIDL.

5. Scheduling service

See https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html — Android task scheduling to learn how to schedule service periodically.

6. Exercise: Using services and service communication

The following example demonstrates how to use a service to download a file from the Internet based on a button click from an activity. Once done, the service notifies the activity via a broadcast receiver that the download is complete.

In this exercise you use the IntentService class, as this class provides automatic background processing.

Create a new project called com.vogella.android.service.receiver with the activity called MainActivity.

Create the following class for the service.

Add this class to the AndroidManifest.xml file. Also add the permission to write to external storage and to access the Internet. The resulting AndroidManifest.xml file should look similar to the following listing.

Change the layout file of your activity to the following.

Change MainActivity to the following.

If you run your example and press the button, the download should be performed by the service. Once done, the user interface is updated and a Toast with the file name is shown.

Change the setting so that the service runs in its own process. Ensure that the application still works, as broadcast receivers are received across process boundaries.

7. Exercise: Define and consume local service

This exercise demonstrates how to bind to a local service from an activity.

The activity binds itself to the service to access its data.

Create a new project called com.vogella.android.localservice with the activity called MainActivity using the Empty Activity template.

Create the following LocalWordService class.

Register your service in the AndroidManifest.xml file.

Change the layout file of the activity similar to the following example.

Change your activity class to the following code.

Run your application. Via your buttons you can update your list or tell the service to fetch more data.

Источник

Читайте также:  Айфон как передать контакты с андроида
Оцените статью