- Планирование задач в Андроид
- Проблемы с сервисами
- Запланированный задачи во время жизненного цикла приложения
- Запланированные задачи при выключенном приложении
- Alarm Manager
- Job Scheduler
- GCM Network Manager
- Firebase Job Dispatcher
- Sync Adapter
- Упражнение
- Создание Job Service
- Создать объект JobInfo
- Запланированная задача
- Заключение
- Job scheduler service android
- Android Job Scheduler Example
- JobService
- Scheduling Job
- Creating JobInfo
- JobScheduler Example
- Android Job Scheduler
- Overview
- Requirements
- Using the Android Job Scheduler
- Implement a JobService
- Creating a JobInfo to schedule a job
- Passing parameters to a job via the JobInfo
- Scheduling a job
- Cancelling a job
- Summary
Планирование задач в Андроид
Привет Хабр! Предлагаю вашему вниманию свободный перевод статьи «Schedule tasks and jobs intelligently in Android» от Ankit Sinhal.
В современной разработке приложений очень часто выполняются задачи асинхронно, и их объем выходит за пределы жизненного цикла приложения. В некоторых ситуациях мы также должны выполнять некоторые работы, но это не обязательно делать прямо сейчас. Чтобы запланировать фоновые работы, Android представила несколько API, которые мы можем грамотно использовать в наших приложениях.
Выбор подходящего планировщика может улучшить производительность приложений и время автономной работы устройства.
Для планирования задач на Android доступно несколько API:
- Alarm Manager
- Job Scheduler
- GCM Network Manager
- Firebase Job Dispatcher
- Sync Adapter
Проблемы с сервисами
Сервисы позволяют выполнять длительные операции в фоновом режиме. Запуск сервисов в фоновом режиме очень негативно влияет на заряд батареии.
Сервисы особенно вредны, когда они постоянно использует ресурсы устройства, даже если не выполняет полезные задачи.
Запланированный задачи во время жизненного цикла приложения
Когда приложение запущено, и мы хотим запланировать или запустить задачу в определенное время, рекомендуется использовать класс Handler вместе с Timer и Thread.
Запланированные задачи при выключенном приложении
Alarm Manager
AlarmManager обеспечивает доступ к службам уведомлений. Это дает возможность выполнять любые операции за пределами жизненного цикла вашего приложения. Таким образом, вы можете инициировать события или действия, даже если ваше приложение не запущено. AlarmManager может запустить сервис в будущем.
Мы должны использовать API AlarmManager только для задач, которые должны выполняться в определенное время
Пример использования: предположим, что мы хотим выполнить задачу через 1 час или каждый час. В этом случае AlarmManager нам поможет.
Job Scheduler
Это главный из всех упомянутых вариантов планирования и очень эффективный с фоновыми работами. JobScheduler API, который был представлен в Android 5.0 (API уровня 21).
Этот API позволяет выполнять задания, когда у устройства больше доступных ресурсов или при соблюдении правильных условий. Все условия могут быть определены при создании задания. Когда объявленные критерии будут выполнены, система выполнит это задание в JobService вашего приложения. JobScheduler также отменяет выполнение, если необходимо, чтобы соблюдать ограничения режима Doze и App Standby.
GCM Network Manager
GCM (Google Cloud Messaging) Network Manager имеет все функции расписания из JobScheduler. GCM Network Manager также предназначен для выполнения многократной или одноразовой, неминуемой работы при сохранении времени автономной работы.
Он используется для поддержки обратной совместимости и может также использоваться под Android 5.0 (API уровня 21). Начиная с уровня API 23 или выше, GCM Network Manager использует JobScheduler для платформы. GCM Network Manager использует механизм планирования в службах Google Play, поэтому этот класс будет работать только в том случае, если на устройстве установлены сервисы Google Play.
Google настоятельно рекомендовал пользователям GCM перейти на FCM и вместо этого использовать диспетчер заданий Firebase для планирования любых задач.
Firebase Job Dispatcher
Firebase JobDispatcher также является библиотекой для планирования фоновых заданий. Он также используется для поддержки обратной совместимости (ниже API 21) и работает во всех последних версиях Android (API 9+).
Эта библиотека также будет работать, если на устройстве нет установленных сервисов Google Play. В этом состоянии эта библиотека внутренне использует AlarmManager. Если на устройстве доступно приложение Google Play, он использует механизм планирования в службах Google Play.
Sync Adapter
Sync adapters разработаны специально для синхронизации данных между устройством и облаком. Он должен использоваться только для этого типа задач. Синхронизация может быть вызвана изменениями данных в облаке или на устройстве или по истекшему времени.
Система будет пытаться синхронизировать только тогда, когда устройство подключено к сети.
Упражнение
Мы обсудили достаточно теории, поэтому теперь посмотрим, как использовать планировщик заданий Android.
Создание Job Service
Создайте JobSchedulerService extends JobService, который требует, чтобы были созданы два метода onStartJob (параметры JobParameters) и onStopJob (параметры JobParameters).
Метод onStartJob вызывается, когда JobScheduler решает запустить вашу работу. JobService работает в основном потоке, поэтому любая логика должна выполняться в отдельном потоке. Метод onStopJob вызывается, если система решила, что вы должны прекратить выполнение своей работы. Метод вызывается до jobFinished (JobParameters, boolean).
Вам также необходимо зарегистрировать свою службу в AndroidManifest.
Создать объект JobInfo
Чтобы построить объект JobInfo, передайте JobService в JobInfo.Builder (), как показано ниже. Этот конструктор заданий позволяет установить множество различных параметров управления при выполнении задания.
Запланированная задача
Теперь у нас есть JobInfo и JobService, поэтому пришло время планировать нашу работу. Все, что нам нужно сделать, это запланировать работу с требуемой JobInfo, как показано ниже:
Заключение
При планировании задания вам нужно тщательно подумать о том, когда и что должно вызвать вашу задачу, и что должно произойти, если она по какой-то причине не сработает. Вы должны быть очень осторожны с производительностью вашего приложения, а также с другими аспектами, такими как заряд батареи.
JobScheduler легко реализуется и обрабатывает большую часть за вас. При использовании JobScheduler наши запланированные задания сохраняются, даже если система перезагружается. В настоящий момент единственным недостатком JobScheduler является то, что он доступен только для 21 уровня api (Android 5.0).
Источник
Job scheduler service android
Android Job Scheduler Example
For scheduling background tasks, Android provides JobScheduler. It allows you to specify conditions for running work. Job schedule is part of android platform and maintains background jobs of all application installed on the device at one place allowing for optimal usage of device resources. JobSchedule can be used to run short and long running tasks such as downloading data, cleaning cache, processing of data, etc.
Now let’s see how you can create and schedule a job using JobScheduler.
JobService
JobService is an android service component with callback methods which the JobSchedule calls when a job needs to be run. That means your background job code needs to be added to callback methods of JobService. To create JobService, you need to extend JobService class and implement its methods onStartJob and onStopJob.
These callback methods are passed JobParameters as an argument by the JobScheduler. JobParameters contains parameters that are set when job is scheduled. These call back methods return boolean value, false indicates that the job is complete and true tells that job is still running in the background, in this case you need to call jobFinished method to inform job scheduler about the finished state after the job is complete.
Since job service is an android component, it runs on main thread. That’s why the tasks which are in job service callback methods needs to be run on background thread.
Since it is a service, you need to define it in the manifest xml file and it needs to be protected with android.permission.BIND_JOB_SERVICE permission.
Scheduling Job
To schedule a job, first you need to get JobScheduler instance by calling getSystemService on the context object passing JOB_SCHEDULER_SERVICE argument to it.
Then you need to instantiate ComponentName object by passing context and job service class that you created.
Then you can create JobInfo object using JobInfo.Builder and setting various configuration parameters. JobInfo.Builder has various setter methods which allow you to define your Job. See the following sections for more details.
Then finally, call schedule() on job scheduler object passing job info object to it.
Creating JobInfo
As shown above JobInfo is created using JobInfo.Builder class by using its setter methods, following are the details.
To create a job that runs every time after elapsing of a specified time, you can use setPeriodic method passing time in milliseconds.
To create a job that needs to be rerun if it fails, you need to use setBackOffCriteria() method passing time interval for the first time retry and retry policy which is used to calculate time interval for retries after first retry.
You can make a job delayed by specified amount of time by setting minimum latency and you can also specify maximum delay by calling setOverrideDeadline. These two setting are applicable for only non-periodic jobs.
To create a job that stays as scheduled even after device reboots, you need call setPersisted() method on JobInfo.Builder passing true as value to it. This setting requires RECEIVE_BOOT_COMPLETED permission.
If your job needs network connection and you want to run the job when network of specified kind is used, then you need to specify required network type by calling setRequiredNetworkType() method passing network type.
You can configure your job to run when the device is charging and idle by calling setRequiresCharging and setRequiresDeviceIdle methods respectively or you can ask the scheduler to not run the job when battery is low by calling setRequiresBatteryNotLow() method and passing true.
Similarly, you can schedule a job to run only when storage is not low by calling setRequiresStorageNotLow() method and setting it to true.
To pass data to JobService, you need to set extras by creating PersistableBundle object. JobScheduler passes PersistableBundle object to JobService call back methods.
JobScheduler Example
I’ll show you how to use JobScheduler in android app with an example. The example job reads latest data from Firebase firestore database, updates device local database with new data and deletes expired data from local database. For local database access, Room persistency library is used.
Источник
Android Job Scheduler
This guide discusses how to schedule background work using the Android Job Scheduler API, which is available on Android devices running Android 5.0 (API level 21) and higher.
Overview
One of the best ways to keep an Android application responsive to the user is to ensure that complex or long running work is performed in the background. However, it is important that background work will not negatively impact the user’s experience with the device.
For example, a background job might poll a website every three or four minutes to query for changes to a particular dataset. This seems benign, however it would have a disastrous impact on battery life. The application will repeatedly wake up the device, elevate the CPU to a higher power state, power up the radios, make the network requests, and then processing the results. It gets worse because the device will not immediately power down and return to the low-power idle state. Poorly scheduled background work may inadvertently keep the device in a state with unnecessary and excessive power requirements. This seemingly innocent activity (polling a website) will render the device unusable in a relatively short period of time.
Android provides the following APIs to help with performing work in the background but by themselves they are not sufficient for intelligent job scheduling.
- Intent Services – Intent Services are great for performing the work, however they provide no way to schedule work.
- AlarmManager – These APIs only allow work to be scheduled but provide no way to actually perform the work. Also, the AlarmManager only allows time based constraints, which means raise an alarm at a certain time or after a certain period of time has elapsed.
- Broadcast Receivers – An Android app can setup broadcast receivers to perform work in response to system-wide events or Intents. However, broadcast receivers don’t provide any control over when the job should be run. Also changes in the Android operating system will restrict when broadcast receivers will work, or the kinds of work that they can respond to.
There are two key features to efficiently performing background work (sometimes referred to as a background job or a job):
- Intelligently scheduling the work – It is important that when an application is doing work in the background that it does so as a good citizen. Ideally, the application should not demand that a job be run. Instead, the application should specify conditions that must be met for when the job can run, and then schedule that job with the operating system that will perform the work when the conditions are met. This allows Android to run the job to ensure maximum efficiency on the device. For example, network requests may be batched to run all at the same time to make maximum use of overhead involved with networking.
- Encapsulating the work – The code to perform the background work should be encapsulated in a discrete component that can be run independently of the user interface and will be relatively easy to reschedule if the work fails to complete for some reason.
The Android Job Scheduler is a framework built in to the Android operating system that provides a fluent API to simplify scheduling background work. The Android Job Scheduler consists of the following types:
- The Android.App.Job.JobScheduler is a system service that is used to schedule, execute, and if necessary cancel, jobs on behalf of an Android application.
- An Android.App.Job.JobService is an abstract class that must be extended with the logic that will run the job on the main thread of the application. This means that the JobService is responsible for how the work is to be performed asynchronously.
- An Android.App.Job.JobInfo object holds the criteria to guide Android when the job should run.
To schedule work with the Android Job Scheduler, a Xamarin.Android application must encapsulate the code in a class that extends the JobService class. JobService has three lifecycle methods that can be called during the lifetime of the job:
bool OnStartJob(JobParameters parameters) – This method is called by the JobScheduler to perform work, and runs on the main thread of the application. It is the responsibility of the JobService to asynchronously perform the work and return true if there is work remaining, or false if the work is done.
When the JobScheduler calls this method, it will request and retain a wakelock from Android for the duration of the job. When the job is finished, it is the responsibility of the JobService to tell the JobScheduler of this fact by call the JobFinished method (described next).
JobFinished(JobParameters parameters, bool needsReschedule) – This method must be called by the JobService to tell the JobScheduler that the work is done. If JobFinished is not called, the JobScheduler will not remove the wakelock, causing unnecessary battery drain.
bool OnStopJob(JobParameters parameters) – This is called when the job is prematurely stopped by Android. It should return true if the job should be rescheduled based on the retry criteria (discussed below in more detail).
It is possible to specify constraints or triggers that will control when a job can or should run. For example, it is possible to constrain a job so that it will only run when the device is charging or to start a job when a picture is taken.
This guide will discuss in detail how to implement a JobService class and schedule it with the JobScheduler .
Requirements
The Android Job Scheduler requires Android API level 21 (Android 5.0) or higher.
Using the Android Job Scheduler
There are three steps for using the Android JobScheduler API:
- Implement a JobService type to encapsulate the work.
- Use a JobInfo.Builder object to create the JobInfo object that will hold the criteria for the JobScheduler to run the job.
- Schedule the job using JobScheduler.Schedule .
Implement a JobService
All work performed by the Android Job Scheduler library must be done in a type that extends the Android.App.Job.JobService abstract class. Creating a JobService is very similar to creating a Service with the Android framework:
- Extend the JobService class.
- Decorate the subclass with the ServiceAttribute and set the Name parameter to a string that is made up of the package name and the name of the class (see the following example).
- Set the Permission property on the ServiceAttribute to the string android.permission.BIND_JOB_SERVICE .
- Override the OnStartJob method, adding the code to perform the work. Android will invoke this method on the main thread of the application to run the job. Work that will take longer that a few milliseconds should be performed on a thread to avoid blocking the application.
- When the work is done, the JobService must call the JobFinished method. This method is how JobService tells the JobScheduler that work is done. Failure to call JobFinished will result in the JobService putting unnecessary demands on the device, shortening the battery life.
- It is a good idea to also override the OnStopJob method. This method is called by Android when the job is being shut down before it is finished and provides the JobService with an opportunity to properly dispose of any resources. This method should return true if it is necessary to reschedule the job, or false if it is not desirable to re-run the job.
The following code is an example of the simplest JobService for an application, using the TPL to asynchronously perform some work:
Creating a JobInfo to schedule a job
Xamarin.Android applications do not instantiate a JobService directly, instead they will pass a JobInfo object to the JobScheduler . The JobScheduler will instantiate the requested JobService object, scheduling and running the JobService according to the metadata in the JobInfo . A JobInfo object must contain the following information:
- JobId – this is an int value that is used to identify a job to the JobScheduler . Reusing this value will update any existing jobs. The value must be unique for the application.
- JobService – this parameter is a ComponentName that explicitly identifies the type that the JobScheduler should use to run a job.
This extension method demonstrates how to create a JobInfo.Builder with an Android Context , such as an Activity:
A powerful feature of the Android Job Scheduler is the ability to control when a job runs or under what conditions a job may run. The following table describes some of the methods on JobInfo.Builder that allow an app to influence when a job can run:
Method | Description |
---|---|
SetMinimumLatency | Specifies that a delay (in milliseconds) that should be observed before a job is run. |
SetOverridingDeadline | Declares the that the job must run before this time (in milliseconds) has elapsed. |
SetRequiredNetworkType | Specifies the network requirements for a job. |
SetRequiresBatteryNotLow | The job may only run when the device is not displaying a «low battery» warning to the user. |
SetRequiresCharging | The job may only run when the battery is charging. |
SetDeviceIdle | The job will run when the device is busy. |
SetPeriodic | Specifies that the job should be regularly run. |
SetPersisted | The job should perisist across device reboots. |
The SetBackoffCriteria provides some guidance on how long the JobScheduler should wait before trying to run a job again. There are two parts to the backoff criteria: a delay in milliseconds (default value of 30 seconds)and type of back off that should be used (sometimes referred to as the backoff policy or the retry policy). The two policies are encapsulated in the Android.App.Job.BackoffPolicy enum:
- BackoffPolicy.Exponential – An exponential backoff policy will increase the initial backoff value exponentially after each failure. The first time a job fails, the library will wait the initial interval that is specified before rescheduling the job – example 30 seconds. The second time the job fails, the library will wait at least 60 seconds before trying to run the job. After the third failed attempt, the library will wait 120 seconds, and so on. This is the default value.
- BackoffPolicy.Linear – This strategy is a linear backoff that the job should be rescheduled to run at set intervals (until it succeeds). Linear backoff is best suited for work that must be completed as soon as possible or for problems that will quickly resolve themselves.
For more details on create a JobInfo object, please read Google’s documentation for the JobInfo.Builder class.
Passing parameters to a job via the JobInfo
Parameters are passed to a job by creating a PersistableBundle that is passed along with the Job.Builder.SetExtras method:
The PersistableBundle is accessed from the Android.App.Job.JobParameters.Extras property in the OnStartJob method of a JobService :
Scheduling a job
To schedule a job, a Xamarin.Android application will get a reference to the JobScheduler system service and call the JobScheduler.Schedule method with the JobInfo object that was created in the previous step. JobScheduler.Schedule will immediately return with one of two integer values:
- JobScheduler.ResultSuccess – The job has been successfully scheduled.
- JobScheduler.ResultFailure – The job could not be scheduled. This is typically caused by conflicting JobInfo parameters.
This code is an example of scheduling a job and notifying the user of the results of the scheduling attempt:
Cancelling a job
It is possible to cancel all the jobs that have been scheduled, or just a single job using the JobsScheduler.CancelAll() method or the JobScheduler.Cancel(jobId) method:
Summary
This guide discussed how to use the Android Job Scheduler to intelligently perform work in the background. It discussed how to encapsulate the work to be performed as a JobService and how to use the JobScheduler to schedule that work, specifying the criteria with a JobTrigger and how failures should be handled with a RetryStrategy .
Источник