All in one scheduler android

Планирование задач в Андроид

Привет Хабр! Предлагаю вашему вниманию свободный перевод статьи «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 разработаны специально для синхронизации данных между устройством и облаком. Он должен использоваться только для этого типа задач. Синхронизация может быть вызвана изменениями данных в облаке или на устройстве или по истекшему времени.
Система будет пытаться синхронизировать только тогда, когда устройство подключено к сети.

Читайте также:  Nintendo 2ds android emulator

Упражнение

Мы обсудили достаточно теории, поэтому теперь посмотрим, как использовать планировщик заданий 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).

Источник

Scheduling of tasks with the Android JobScheduler — Tutorial

This tutorial describes how to schedule tasks in Android with the JobScheduler API.

1. Scheduling tasks

1.1. Options for scheduling

If you have a repetitive task in your Android app, you need to consider that activities and services can be terminated by the Android system to free up resources. Therefore you can not rely on standard Java schedule like the TimerTasks class.

The Android system currently has two main means to schedule tasks:

the (outdated) AlarmManager

the JobScheduler API.

Modern Android applications should use the JobScheduler API. Apps can schedule jobs while letting the system optimize based on memory, power, and connectivity conditions.

1.2. The job scheduler API

The Android 5.0 Lollipop (API 21) release introduces a job scheduler API via the JobScheduler class. This API allows to batch jobs when the device has more resources available. In general this API can be used to schedule everything that is not time critical for the user.

1.3. Advantages of the job scheduler API

Compared to a custom SyncAdapter or the alarm manager , the JobScheduler supports batch scheduling of jobs. The Android system can combine jobs so that battery consumption is reduced. JobManager makes handling uploads easier as it handles automatically the unreliability of the network. It also survives application restarts. Here are example when you would use this job scheduler:

Tasks that should be done once the device is connect to a power supply

Tasks that require network access or a Wi-Fi connection.

Task that are not critical or user facing

Tasks that should be running on a regular basis as batch where the timing is not critical

1.4. Create a Job

A unit of work is encapsulated by a JobInfo object. This object specifies the scheduling criteria. The job scheduler allows to consider the state of the device, e.g., if it is idle or if network is available at the moment. Use the JobInfo.Builder class to configure how the scheduled task should run. You can schedule the task to run under specific conditions, such as:

Device is charging

Device is connected to an unmetered network

Start before a certain deadline

Start within a predefined time window, e.g., within the next hour

Start after a minimal delay, e.g., wait a minimum of 10 minutes

These constraints can be combined. For example, you can schedule a job every 20 minutes, whenever the device is connected to an unmetered network. Deadline is a hard constraint, if that expires the job is always scheduled.

Читайте также:  Джойстик ps4 для андроида

To implement a Job, extend the JobService class and implement the onStartJob and onStopJob . If the job fails for some reason, return true from on the onStopJob to restart the job. The onStartJob is performed in the main thread, if you start asynchronous processing in this method, return true otherwise false .

The new JobService must be registered in the Android manifest with the BIND_JOB_SERVICE permission.

Источник

Schedule tasks and jobs intelligently in Android

Jun 1, 2017 · 6 min read

In the modern application development, it is very common for our application to perform tasks asynchronously and scope of them are outside the application’s life-cycle like downloading some data or updating network resources. In some situations we also have to do some work but it is not required to do it right now. To schedule background work, Android introduced several APIs which we can use wisely in our applications.

Selecting a proper scheduler can improve application performance and battery life of the device.

Android M also in t roduced Doze mode to minimize battery drain while user has been away from device for a period of time.

There are several APIs available to schedule tasks in Android:

  • Alarm Manager
  • Job Scheduler
  • GCM Network Manager
  • Firebase Job Dispatcher
  • Sync Adapter

Problems with Services

Services allows you to perform long-running operations in the background. Running services in the background is very expensive for the battery life of the device.

Services are especially harmful when it continuously uses device resources even when not performing useful tasks. Above problem increased when those background services are listening for different system broadcasts (like CONNECTIVITY_CHANGE or NEW_PICTURE etc.).

Schedule task in lifetime of your app

When application is running and we want to schedule or run a task at a specific time then it is recommended to use Handler class in conjunction with Timer and Thread. Instead of using Alarm Manger, Job Scheduler etc. it is easier and much more efficient to use Handler.

Schedule task outside the lifetime of your app

Alarm Manager

AlarmManager provides access to system-level alarm services. This give a way to perform any operations outside the lifetime of your application. So you can trigger events or actions even when your application is not running. AlarmManager can startup a service in future. It is used to trigger a PendingIntent when alarm goes off.

Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

“We should only use AlarmManager API for tasks that must execute at a specific time. This does not provide more robust execution conditions like device is idle, network is available or charging detect.”

Use Case: Let’s say we want to perform a task after 1 hour or every 1 hour. In this case AlarmManager works perfectly for us. But this API is not suitable in a situations like perform the above task only when network is available or when device is not charging.

Job Scheduler

This is the chief among all the mentioned scheduling options and perform the background work very efficiently. JobScheduler API which was introduced in Android 5.0(API level 21).

This API allows to batch jobs when the device has more resources available or when the right conditions are met. All of the conditions can be defined when you’re creating a job. When the criteria declared are met, the system will execute this job on your application’s JobService. JobScheduler also defers the execution as necessary to comply with Doze mode and App Standby restrictions.

Batching job execution in this fashion allows the device to enter and stay in sleep states longer, preserving battery life. In general this API can be used to schedule everything that is not time critical for the user.

GCM Network Manager

GCM (Google Cloud Messaging) Network Manager has all the schedule features from JobScheduler. GCM Network Manager is also meant for performing repeated or one-off, non-imminent work while keeping battery life in mind.

Читайте также:  Иос перенос с андроида

It is used to support backward compatibility and can also use below Android 5.0 (API level 21). From API level 23 or higher, GCM Network Manager uses the framework’s JobScheduler. GCM Network Manager uses the scheduling engine inside Google Play services so this class will only work if the Google Play services is installed on the device.

Google has strongly recommended for GCM users to upgrade to FCM and instead use Firebase Job Dispatcher for scheduling any tasks.

Firebase Job Dispatcher

The Firebase JobDispatcher is also a library for scheduling background jobs. It is also used to support backward compatibility (below API level 21) and works on all recent versions of Android (API level 9+).

This library will also works when running device do not have Google play services installed and wants to schedule a job in the application. In this condition this library internally uses AlarmManager. If Google Play service is available on the device then it uses the scheduling engine inside Google Play services.

Sync adapters are designed specifically for syncing data between a device and the cloud. It should be only use for this type of task. Syncs could be triggered from data changes in either the cloud or device, or by elapsed time and time of day. The Android system will try to batch outgoing syncs to save battery life and transfers that are unable to run will queue up for transfer at some later time. The system will attempt syncs only when the device is connected to a network.

Wherever possible, it is advised via Google to use JobScheduler, Firebase JobDispatcher, or GCM Network Manager.

In Android N (API level 24), the SyncManager sits on top of the JobScheduler. You should only use the SyncAdapter class if you require the additional functionality that it provides.

Exercise

We discussed lots of theoretical things so now have a look how to use the Android job scheduler.

1. Creating the Job Service

Create JobSchedulerService and extend the JobService class, which requires that two methods be created onStartJob(JobParameters params) and onStopJob(JobParameters params).

The method onStartJob(JobParameters params) gets called when the JobScheduler decides to run your job. The JobService runs on the main thread so any logic needs to be performed should be in a separate thread. Method onStopJob(JobParameters params) gets called if the system determined that you must stop execution of your job even before you’ve had a chance to call jobFinished(JobParameters, boolean).

You also have to register your job service in the AndroidManifest.

2. Create JobInfo object

To construct a JobInfo object, pass the JobService into JobInfo.Builder() as shown below. This job builder allows to set many different options for controlling when job executes.

Now we have JobInfo and JobService so it is time to schedule our job. All we need to do is to schedule a job with desired JobInfo as shown below:

You can download the complete source code of JobSchedulerExample from GitHub.

Conclusion

While scheduling a job, you’ll need to think carefully about when and what should trigger your job and what should happen if it fails for some reason. You have to be very careful with your app performance along with other aspects such as battery life.

JobScheduler is easy to implement and handle most of the complexity for you. While using JobScheduler, our scheduled jobs persists even if system reboots. At this moment the only downside of JobScheduler is that it is only available for api level 21 (Android 5.0).

Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful.

Stay tuned for upcoming articles. For any quires or suggestions, feel free to hit me on Twitter Google+ LinkedIn

Check out my blogger page for more interesting topics on Software development.

Источник

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