- Планирование задач в Андроид
- Проблемы с сервисами
- Запланированный задачи во время жизненного цикла приложения
- Запланированные задачи при выключенном приложении
- Alarm Manager
- Job Scheduler
- GCM Network Manager
- Firebase Job Dispatcher
- Sync Adapter
- Упражнение
- Создание Job Service
- Создать объект JobInfo
- Запланированная задача
- Заключение
- Humble Bits
- How to Schedule Jobs in Android using FireBase Job Dispatcher?
- Cancel a Job
- Android studio firebase jobdispatcher
Планирование задач в Андроид
Привет Хабр! Предлагаю вашему вниманию свободный перевод статьи «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).
Источник
Humble Bits
How to Schedule Jobs in Android using FireBase Job Dispatcher?
Recently I worked on a project where I needed to perform a task once after every 3 hours of using the application. I thought of using the AlarmManager for this. Later I got to know that the task should also be performed whenever the network is available. In which case, AlarmManager will not be able to take care of the additional requirement.
Although Android provides us the GcmNetworkManager for the network availability requirement, there is another challenge while using GcmNetworkManager where a user doesn’t have Google play services installed in his/her mobile. I know that it is rare that Android mobiles don’t have Google play services but I can’t take that risk. So I decided to use Android JobScheduler that is more suitable for these kinds of constraints. JobScheduler works great when our app wants to perform a specific task only in cases when-
1. User’s mobile gets connected to power supply.
2. There is a network availability.
However, JobScheduler only works with API level >=21. Our app supports the earlier versions too, so JobScheduler also wasn’t able to fulfill my requirement.
Then, I came to know about FireBase Job Dispatcher which not only works the same as Android JobScheduler but also provides compatibility for lower versions. FireBase Job Dispatcher uses the same framework as of Android JobScheduler. I am using it in my project and it’s working like a charm.
All of us know about AlarmManager which is present from Android version 1. Later we saw some changes were made to save the battery of the device and boost the performance. The biggest issue with AlarmManager is that it works on the basis of time. For this issue, Google introduced JobScheduler which works well in most of the common conditions like charging of the device, availability of the network.
But we have another condition while using JobSchedular i.e. minimum SDK version must be >=21. What about for the app having minimum SDK version JobService subclass that will contain all the business logic related to the Job.
default is to keep the Job scheduled until the next boot.
with the same tag or not. The default value for this boolean flag is false.
Once your job is ready, you can use schedule() method to schedule the job.
There are three methods that will be used while using FireBase Job Dispatcher.
onStartJob(JobParameters params)-This is the initial method that will be invoked when a job is called. It runs on the main thread. It will return a Boolean which tells whether a job is remaining or not. Returning true indicates that more work is remaining. We can call jobFinished() as soon as the job is completed.
onStopJob(JobParameters params)- This method is called when your job is stopped. The job can be stopped due to various reasons like if the running constraints associated with the job are no longer satisfied. It will return a Boolean which tells whether a job should be tried again or not. If returned true, then the framework will put up this job again for execution.
jobFinished(JobParameters params, boolean needsReschedule)-When job has been offloaded to a new thread, it should be called explicitly.
Cancel a Job
A job can be canceled using c ancel() method by passing the tag as the argument.
If you need to cancel all the jobs for your application package then call cancelAll() method.
That’s all about FireBase Job Dispatcher. Hope you have fun using it!
Источник
Android studio firebase jobdispatcher
This repository has been archived and is no longer maintained.
Update: April 2019
Last year, we announced Android Jetpack WorkManager. WorkManager, the new job management system in Jetpack, incorporates the features of Firebase Job Dispatcher (FJD) and Android’s JobScheduler to provide a consistent job scheduling service back to api level 14 while leveraging JobScheduler on newer devices. WorkManager works with or without Google Play Services, which is something FJD cannot do. WorkManager was first released to alpha in May 2018 and then went thru extensive iteration and improvement based on developer feedback including 10 alphas; it moved to beta on Dec 19, 2018, and was released to stable on Mar 5, 2019. One thing the team has been discussing at some length is whether it would be better for developers in the long run if we create one holistic solution via WorkManager; where we can pool all of our efforts and also give developers a single unified recommended path?
After careful evaluation, the team has decided to focus all of our efforts on WorkManager and to deprecate Firebase Job Dispatcher. We have modified our plans in direct response to developer feedback in order to make this as easy for you as possible. We know that managing background work is a critical part of your app and these changes impact you. We want to support you through this migration as much as we can by giving you as much advance notice as possible to make these changes. Firebase Job Dispatcher will be archived in github in about 1 year, on Apr 7, 2020. Apps should migrate to WorkManager or an alternative job management system before this date.
We’ve created a detailed migration guide to assist you in the transition to WorkManager. After Apr 7, 2020, this github repository will be archived and support for FJD customer issues will stop. Additionally, FJD will stop working once your app starts targeting an Android version after Android Q.
We are continuing to invest in and add new features to WorkManager and welcome any feedback or feature requests.
The Firebase JobDispatcher is a library for scheduling background jobs in your Android app. It provides a JobScheduler-compatible API that works on all recent versions of Android (API level 14+) that have Google Play services installed.
The JobScheduler is an Android system service available on API levels 21 (Lollipop)+. It provides an API for scheduling units of work (represented by JobService subclasses) that will be executed in your app’s process.
Why is this better than background services and listening for system broadcasts?
Running apps in the background is expensive, which is especially harmful when they’re not actively doing work that’s important to the user. That problem is multiplied when those background services are listening for frequently sent broadcasts ( android.net.conn.CONNECTIVITY_CHANGE and android.hardware.action.NEW_PICTURE are common examples). Even worse, there’s no way of specifying prerequisites for these broadcasts. Listening for CONNECTIVITY_CHANGE broadcasts does not guarantee that the device has an active network connection, only that the connection was recently changed.
In recognition of these issues, the Android framework team created the JobScheduler. This provides developers a simple way of specifying runtime constraints on their jobs. Available constraints include network type, charging state, and idle state.
This library uses the scheduling engine inside Google Play services(formerly the GCM Network Manager component) to provide a backwards compatible (back to Gingerbread) JobScheduler-like API.
This I/O presentation has more information on why background services can be harmful and what you can do about them:
There’s more information on upcoming changes to Android’s approach to background services on the Android developer preview page.
The FirebaseJobDispatcher currently relies on the scheduling component in Google Play services. Because of that, it won’t work on environments without Google Play services installed.
Comparison to other libraries
Library | Minimum API | Requires Google Play | Service API 1 | Custom retry strategies |
---|---|---|---|---|
Framework JobScheduler | 21 | No | JobScheduler | Yes |
Firebase JobDispatcher | 14 | Yes | JobScheduler | Yes |
evernote/android-job | 14 | No 2 | Custom | Yes |
Android WorkManager 3 | 14 | No 2 | Custom | Yes |
1 Refers to the methods that need to be implemented in the Service subclass.
2 Uses AlarmManager or JobScheduler to support API levels 3 Currently in alpha phase, soon to graduate to beta.
Источник