Doing a job in background is very critical, specially with Doze mode and App stand by. In this presentation I have explained how can you schedule a job intelligently and conserve user's battery and network data.
1) Intents represent requests for actions to be performed, while Intent Filters register which app components can handle certain actions and types of data.
2) Broadcast receivers listen for broadcast intents and allow interaction between app components.
3) Intents are used to start activities, broadcast messages, and launch other apps like the Android Market. Intent Filters are required for intent resolution and matching intents to the correct components.
The document discusses Android threading and how to handle long running tasks to avoid blocking the UI thread. It covers the main UI thread, how to run tasks on a background thread using Thread and Runnable, and how to update the UI from the background thread using runOnUiThread(), post(), postDelayed() and AsyncTask. AsyncTask is recommended as it handles threading for you by running background tasks on a worker thread and calling publishProgress() to update the UI on the main thread.
This is a basic crash course for android development covers:
Android Studio,Hello World Application,Application Components,Application Resources,User Interface,Good UI,Play Store
The document discusses the Android application framework. It includes core libraries that provide functionality like media playback, 2D/3D graphics, and SQLite. The Dalvik VM was used before Android 5 but has been replaced by ART, which uses ahead-of-time compilation. The framework includes activities, intents, services, and content providers as important app components. It also handles notifications, audio/video output, and surfaces using managers. Fragments allow dividing an activity's UI.
The document discusses various sensors available on Android devices. It describes the accelerometer, gravity sensor, linear acceleration sensor, magnetic field sensor, orientation sensor, gyroscope, light sensor, proximity sensor, temperature sensor, pressure sensor, and other sensors. It provides details on what each sensor measures and how it can be used. It also covers sensor fusion and the Android sensor framework.
- Foreground services run in the foreground and can avoid being recycled by the Android system when low on resources. They can be interacted with by the user through notifications.
- Started services run indefinitely in the background until stopped or destroyed by the system. They are launched by other app components like activities or broadcast receivers.
- Bound services can return results and interact with the component that started them, unlike started services. They allow sending data to the launching component.
- IPC allows two processes or apps to communicate by passing data. On Android, processes cannot access each other's memory directly, so IPC provides channels for communication using messengers or AIDL.
Fragments allow modularizing an app's UI into reusable components. A fragment represents a portion of UI within an activity and has its own lifecycle. Multiple fragments can be used within a single activity to create a multi-pane UI or reuse fragments across activities. Key advantages are modularity, ability to reuse fragments, and maintaining a back stack of fragment states. The document discusses implementing fragments in different screen types, writing fragment and activity classes, and including fragments in layouts. It also covers fragment types like ListFragment and DialogFragment and ensuring compatibility by adding the support library.
The document discusses the different building blocks of an Android application including activities, services, broadcast receivers, and content providers. It provides details on broadcast receivers, describing them as components that respond to system-wide broadcasts and application-initiated broadcasts. The document gives an example of using a broadcast receiver to capture the SMS receive event and launch an activity to display the SMS with an option to reply. It also discusses programmatically sending SMS from an application.
1) Intents represent requests for actions to be performed, while Intent Filters register which app components can handle certain actions and types of data.
2) Broadcast receivers listen for broadcast intents and allow interaction between app components.
3) Intents are used to start activities, broadcast messages, and launch other apps like the Android Market. Intent Filters are required for intent resolution and matching intents to the correct components.
The document discusses Android threading and how to handle long running tasks to avoid blocking the UI thread. It covers the main UI thread, how to run tasks on a background thread using Thread and Runnable, and how to update the UI from the background thread using runOnUiThread(), post(), postDelayed() and AsyncTask. AsyncTask is recommended as it handles threading for you by running background tasks on a worker thread and calling publishProgress() to update the UI on the main thread.
This is a basic crash course for android development covers:
Android Studio,Hello World Application,Application Components,Application Resources,User Interface,Good UI,Play Store
The document discusses the Android application framework. It includes core libraries that provide functionality like media playback, 2D/3D graphics, and SQLite. The Dalvik VM was used before Android 5 but has been replaced by ART, which uses ahead-of-time compilation. The framework includes activities, intents, services, and content providers as important app components. It also handles notifications, audio/video output, and surfaces using managers. Fragments allow dividing an activity's UI.
The document discusses various sensors available on Android devices. It describes the accelerometer, gravity sensor, linear acceleration sensor, magnetic field sensor, orientation sensor, gyroscope, light sensor, proximity sensor, temperature sensor, pressure sensor, and other sensors. It provides details on what each sensor measures and how it can be used. It also covers sensor fusion and the Android sensor framework.
- Foreground services run in the foreground and can avoid being recycled by the Android system when low on resources. They can be interacted with by the user through notifications.
- Started services run indefinitely in the background until stopped or destroyed by the system. They are launched by other app components like activities or broadcast receivers.
- Bound services can return results and interact with the component that started them, unlike started services. They allow sending data to the launching component.
- IPC allows two processes or apps to communicate by passing data. On Android, processes cannot access each other's memory directly, so IPC provides channels for communication using messengers or AIDL.
Fragments allow modularizing an app's UI into reusable components. A fragment represents a portion of UI within an activity and has its own lifecycle. Multiple fragments can be used within a single activity to create a multi-pane UI or reuse fragments across activities. Key advantages are modularity, ability to reuse fragments, and maintaining a back stack of fragment states. The document discusses implementing fragments in different screen types, writing fragment and activity classes, and including fragments in layouts. It also covers fragment types like ListFragment and DialogFragment and ensuring compatibility by adding the support library.
The document discusses the different building blocks of an Android application including activities, services, broadcast receivers, and content providers. It provides details on broadcast receivers, describing them as components that respond to system-wide broadcasts and application-initiated broadcasts. The document gives an example of using a broadcast receiver to capture the SMS receive event and launch an activity to display the SMS with an option to reply. It also discusses programmatically sending SMS from an application.
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaJAX London
2011-11-02 | 03:45 PM - 04:35 PM |
Android Activities can possess one of four launch modes and one of many activity tasks. We will explore how your choices of launch modes and tasks affect your Applications back stack history and what will happen behind the scenes. After this talk you will confidently be able to wield the best launch modes for your apps activities in every situation!
Kotlin Coroutines allow for writing asynchronous non-blocking code using coroutines and suspending functions. Key features include cooperative multitasking on a single thread, using coroutines instead of threads, and dispatchers to control coroutine execution. Examples demonstrate loading data asynchronously for UI, updating multiple objects concurrently using coroutines, and checking server validity in a non-blocking suspending function.
The document discusses the Dalvik virtual machine (VM) used in Android. It begins by explaining what a VM is and the basic parts that make up a VM. It then discusses the differences between stack-based and register-based VMs, noting that Dalvik uses a register-based architecture. The document explains that Dalvik was chosen for Android because it executes faster than Java VM and uses less memory. It also describes how Java bytecodes are converted to Dalvik bytecodes and discusses optimizations like shared constant pools and just-in-time compilation that improve Dalvik's performance.
This document introduces Android AIDL (Android Interface Definition Language), which allows for inter-process communication (IPC) between Android applications. It discusses writing AIDL interface and implementation files to define service interfaces and how to use AIDL to allow an app's services to be bound by other apps. The key aspects covered are the supported data types in AIDL, how AIDL addresses IPC memory issues, and how to generate AIDL interface implementations to make remote calls between processes using AIDL.
Android Intents allow communication between app components and sharing of data. An Intent specifies an action and can contain data and extras. There are explicit intents, which target a specific component, and implicit intents, which specify an action that may be handled by multiple apps. Components declare intent filters in the manifest to receive implicit intents matching the filter's action, data, and category. When an implicit intent is received, the system resolves matching components by comparing the intent to intent filters.
Dialogs in Android are small windows that prompt users to take an action or enter information before proceeding. There are several types of dialogs including alerts, popups, and toasts. Alerts inform users and require a response while popups require a single selection. Toasts provide lightweight feedback. The example shows how to create an alert dialog using a Builder pattern to set the message, buttons, and listeners.
Android services allow long-running tasks to perform work in the background independently of an application's user interface. There are two main types of services: started services which can perform operations indefinitely even if the starting component is destroyed, and bound services which offer a client-server interface between a component and the service. Services must be started with startService() or bound to with bindService() and have lifecycle callback methods like onStartCommand(), onBind(), onCreate(), and onDestroy(). The IntentService class simplifies started service implementation. Bound services can expose interfaces using Binder, Messenger, or AIDL to allow inter-process communication.
The document provides an overview of Android's multimedia framework. It discusses the architecture basics, including the display core, multimedia architecture, app development model, kernel drivers, HAL definitions and modules, system services like Stagefright, relevant apps, and references. The display core section specifically describes the display hardware, stack, kernel driver, HAL definition and module, SurfaceFlinger, and WindowManager.
The document discusses the basic components of an Android app. It explains that an Android app consists of components like activities, services, broadcast receivers, and content providers. Activities provide the main user interface and common ones include launching the app and navigating within it. The app manifest file defines these components. The document also covers activities and intents, explaining how activities are launched via explicit and implicit intents and how data can be passed between activities.
Slides from Android Builder's Summit 2014 in San Jose, CA
In this talk I describe the internal workings of the Android graphics stack from the Application layer down through the stack to pixels on the screen. It is a fairly complex journey, taking in two different 2D rendering engines, applications calling OpenGL ES directory, passing buffers on to the system compositor, SurfaceFlinger, and then down to the display controller or frame buffer.
Android uses Views and ViewGroups to create user interfaces. Views occupy rectangular areas on screen and handle drawing and events. Common widgets like Buttons and TextViews are subclasses of View. Layouts like LinearLayout and RelativeLayout are ViewGroups that position child Views. Layout parameters specify how Views are positioned. Common event listeners include onClick and onTouch, which call registered event handlers when triggered by user interaction.
Fragments allow modular sections of an activity's UI to be reused across activities and configurations. A fragment must be embedded in an activity and shares its lifecycle. Fragments can be added or removed dynamically at runtime and their transactions can be added to a back stack. Activities can combine multiple fragments to build a multi-pane UI on tablets and reuse fragments across activities on handsets. To create a fragment, subclass Fragment and move code from activities into fragment lifecycle methods.
A service in Android runs in the background without a user interface. It can be started and stopped to perform long-running operations like playing audio. A service is not a separate process or a thread but allows work to be done in the background even when the user is not interacting with the app. The document provides an example service app that runs a background service displaying a notification every 5 seconds until stopped. It demonstrates starting and stopping the service from an activity and handling the service lifecycle through onCreate(), onStart(), and onDestroy() methods.
This document discusses different types of notifications in Android, including toast notifications, status bar notifications, and alarm manager notifications. It provides code examples for creating each type. Toast notifications display temporary messages on screen without user interaction. Status bar notifications add icons and messages to the status bar that expand when pulled down, and can launch an activity when clicked. The alarm manager allows triggering notifications at specific times in the future.
The AlarmManager API allows applications to schedule code to run at some point in the future even if the application is not actively running. Alarms can be set to repeat at intervals like every 15 minutes or every hour. Alarms remain active even when the device is asleep and can optionally wake the device. The AlarmManager is accessed through the Context and allows setting one-shot or repeating alarms to launch activities, broadcasts, or services at the scheduled time.
This document discusses Android AsyncTask, which allows performing long/background operations without threads. It has four main methods: doInBackground runs the long operation, onPostExecute displays results after completion, onPreExecute runs before doInBackground, and onProgressUpdate reports progress. An example AsyncTask downloads files, tracking progress in onProgressUpdate and displaying results in onPostExecute after doInBackground finishes downloading. AsyncTask requires specifying types for parameters, progress, and results.
The document discusses the activity lifecycle in Android, describing the different states an activity can be in (starting, running, paused, stopped, destroyed) and the methods called during transitions between these states (onCreate, onPause, onResume, onStop, onDestroy). It provides details on the role and proper use of each method, such as initializing resources in onCreate, stopping animations in onPause, and releasing resources in onDestroy. Logging with LogCat is also described as a way to test activity state changes.
The document discusses the JobScheduler API introduced in Android 5.0, which allows scheduling jobs to run when device conditions are met. This allows batching jobs and being considerate of battery life, unlike the AlarmManager which requires exact timing. Jobs can be scheduled to run when the device is charging, on unmetered network, idle, before a deadline, or after a delay. The JobService methods onStartJob and onStopJob are used to start and cancel jobs. A JobScheduler is created and JobInfo objects define job parameters and constraints.
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaJAX London
2011-11-02 | 03:45 PM - 04:35 PM |
Android Activities can possess one of four launch modes and one of many activity tasks. We will explore how your choices of launch modes and tasks affect your Applications back stack history and what will happen behind the scenes. After this talk you will confidently be able to wield the best launch modes for your apps activities in every situation!
Kotlin Coroutines allow for writing asynchronous non-blocking code using coroutines and suspending functions. Key features include cooperative multitasking on a single thread, using coroutines instead of threads, and dispatchers to control coroutine execution. Examples demonstrate loading data asynchronously for UI, updating multiple objects concurrently using coroutines, and checking server validity in a non-blocking suspending function.
The document discusses the Dalvik virtual machine (VM) used in Android. It begins by explaining what a VM is and the basic parts that make up a VM. It then discusses the differences between stack-based and register-based VMs, noting that Dalvik uses a register-based architecture. The document explains that Dalvik was chosen for Android because it executes faster than Java VM and uses less memory. It also describes how Java bytecodes are converted to Dalvik bytecodes and discusses optimizations like shared constant pools and just-in-time compilation that improve Dalvik's performance.
This document introduces Android AIDL (Android Interface Definition Language), which allows for inter-process communication (IPC) between Android applications. It discusses writing AIDL interface and implementation files to define service interfaces and how to use AIDL to allow an app's services to be bound by other apps. The key aspects covered are the supported data types in AIDL, how AIDL addresses IPC memory issues, and how to generate AIDL interface implementations to make remote calls between processes using AIDL.
Android Intents allow communication between app components and sharing of data. An Intent specifies an action and can contain data and extras. There are explicit intents, which target a specific component, and implicit intents, which specify an action that may be handled by multiple apps. Components declare intent filters in the manifest to receive implicit intents matching the filter's action, data, and category. When an implicit intent is received, the system resolves matching components by comparing the intent to intent filters.
Dialogs in Android are small windows that prompt users to take an action or enter information before proceeding. There are several types of dialogs including alerts, popups, and toasts. Alerts inform users and require a response while popups require a single selection. Toasts provide lightweight feedback. The example shows how to create an alert dialog using a Builder pattern to set the message, buttons, and listeners.
Android services allow long-running tasks to perform work in the background independently of an application's user interface. There are two main types of services: started services which can perform operations indefinitely even if the starting component is destroyed, and bound services which offer a client-server interface between a component and the service. Services must be started with startService() or bound to with bindService() and have lifecycle callback methods like onStartCommand(), onBind(), onCreate(), and onDestroy(). The IntentService class simplifies started service implementation. Bound services can expose interfaces using Binder, Messenger, or AIDL to allow inter-process communication.
The document provides an overview of Android's multimedia framework. It discusses the architecture basics, including the display core, multimedia architecture, app development model, kernel drivers, HAL definitions and modules, system services like Stagefright, relevant apps, and references. The display core section specifically describes the display hardware, stack, kernel driver, HAL definition and module, SurfaceFlinger, and WindowManager.
The document discusses the basic components of an Android app. It explains that an Android app consists of components like activities, services, broadcast receivers, and content providers. Activities provide the main user interface and common ones include launching the app and navigating within it. The app manifest file defines these components. The document also covers activities and intents, explaining how activities are launched via explicit and implicit intents and how data can be passed between activities.
Slides from Android Builder's Summit 2014 in San Jose, CA
In this talk I describe the internal workings of the Android graphics stack from the Application layer down through the stack to pixels on the screen. It is a fairly complex journey, taking in two different 2D rendering engines, applications calling OpenGL ES directory, passing buffers on to the system compositor, SurfaceFlinger, and then down to the display controller or frame buffer.
Android uses Views and ViewGroups to create user interfaces. Views occupy rectangular areas on screen and handle drawing and events. Common widgets like Buttons and TextViews are subclasses of View. Layouts like LinearLayout and RelativeLayout are ViewGroups that position child Views. Layout parameters specify how Views are positioned. Common event listeners include onClick and onTouch, which call registered event handlers when triggered by user interaction.
Fragments allow modular sections of an activity's UI to be reused across activities and configurations. A fragment must be embedded in an activity and shares its lifecycle. Fragments can be added or removed dynamically at runtime and their transactions can be added to a back stack. Activities can combine multiple fragments to build a multi-pane UI on tablets and reuse fragments across activities on handsets. To create a fragment, subclass Fragment and move code from activities into fragment lifecycle methods.
A service in Android runs in the background without a user interface. It can be started and stopped to perform long-running operations like playing audio. A service is not a separate process or a thread but allows work to be done in the background even when the user is not interacting with the app. The document provides an example service app that runs a background service displaying a notification every 5 seconds until stopped. It demonstrates starting and stopping the service from an activity and handling the service lifecycle through onCreate(), onStart(), and onDestroy() methods.
This document discusses different types of notifications in Android, including toast notifications, status bar notifications, and alarm manager notifications. It provides code examples for creating each type. Toast notifications display temporary messages on screen without user interaction. Status bar notifications add icons and messages to the status bar that expand when pulled down, and can launch an activity when clicked. The alarm manager allows triggering notifications at specific times in the future.
The AlarmManager API allows applications to schedule code to run at some point in the future even if the application is not actively running. Alarms can be set to repeat at intervals like every 15 minutes or every hour. Alarms remain active even when the device is asleep and can optionally wake the device. The AlarmManager is accessed through the Context and allows setting one-shot or repeating alarms to launch activities, broadcasts, or services at the scheduled time.
This document discusses Android AsyncTask, which allows performing long/background operations without threads. It has four main methods: doInBackground runs the long operation, onPostExecute displays results after completion, onPreExecute runs before doInBackground, and onProgressUpdate reports progress. An example AsyncTask downloads files, tracking progress in onProgressUpdate and displaying results in onPostExecute after doInBackground finishes downloading. AsyncTask requires specifying types for parameters, progress, and results.
The document discusses the activity lifecycle in Android, describing the different states an activity can be in (starting, running, paused, stopped, destroyed) and the methods called during transitions between these states (onCreate, onPause, onResume, onStop, onDestroy). It provides details on the role and proper use of each method, such as initializing resources in onCreate, stopping animations in onPause, and releasing resources in onDestroy. Logging with LogCat is also described as a way to test activity state changes.
The document discusses the JobScheduler API introduced in Android 5.0, which allows scheduling jobs to run when device conditions are met. This allows batching jobs and being considerate of battery life, unlike the AlarmManager which requires exact timing. Jobs can be scheduled to run when the device is charging, on unmetered network, idle, before a deadline, or after a delay. The JobService methods onStartJob and onStopJob are used to start and cancel jobs. A JobScheduler is created and JobInfo objects define job parameters and constraints.
The document summarizes the top 10 new features in Android M:
1. Android M preview timeline and expected Q3 2015 release.
2. Changes to app permissions including runtime permissions and reduced install/update friction.
3. How to properly request and handle permissions.
4. New fingerprint API and authentication without sharing credentials.
5. Doze mode for better battery life when idle and postponing non-important tasks.
The document discusses Android job scheduling and provides details about the JobScheduler API. It defines scheduling, compares the AlarmManager and JobScheduler, and describes how to implement and schedule jobs using the JobScheduler. Examples are provided to demonstrate how to create a JobService, schedule jobs with criteria like network availability, and ensure jobs are persisted across device reboots.
Android Best Practices - Thoughts from the TrenchesAnuradha Weeraman
Here are some of the key structural building blocks in Android that can be used to build the YAMBA app:
1. Activities - For the timeline view and preference screens.
2. Services - For the background process that fetches statuses from the server. This can be started on boot and stopped based on network connectivity.
3. ContentProviders - To store and retrieve statuses from local storage.
4. BroadcastReceivers - To listen for boot completed and network connectivity changes. Can start/stop the background service accordingly.
5. AsyncTasks - For fetching statuses from the server in the background without blocking the UI.
6. Intents - To start the background service from the BroadcastReceivers
Google I/O 2019 - what's new in Android Q and JetpackSunita Singh
Google IO 2019 highlighted several new Android features including Bubbles for easy multi-tasking, dark theme support, sharing improvements, and gesture navigation. It also provided updates on Jetpack components like CameraX, Navigation, Compose, ViewPager 2, ViewBindings and WorkManager to improve development. Machine learning was expanded through updates to MLKit and new features for on-device translation and object detection.
A presentation on how and when to use a WorkManager in Android. This presentation gives deep insight into what type of background service we can use in the background.
We delve deep into working and functionalities provided by WorkManger and see how we can add One-Time and Periodic tasks along with various constraints we can set to initialization of a worker.
04 programmation mobile - android - (db, receivers, services...)TECOS
The document discusses content providers, databases, broadcast receivers, services, and notifications in Android mobile app development. Content providers manage access to structured app data and allow sharing data between processes. SQLite is used for databases, with methods like query, insert, update. Broadcast receivers listen for system/app events, services run background tasks, and notifications display messages outside the app UI.
As presented during droidcon.de 2015
As an Android developers we use various frameworks and libraries provided by Google and others. Sometimes they are just a pure magic (say hi to Jake Wharton and his ActionBarShelock!) and sometimes… Well, if we make an effort to grap the source code and go through it, we realise there is no magic there. During my presentation, I will go deep into Lollipop’s new JobScheduler API. See what’s really there, how it’s advertised, and try to assess how big is the gap between us and guys at Google. Should we have any inferiority complex or could we write this code ourselves?
1) Background agents allow Windows Phone applications to perform tasks even when they are not in the foreground. There are two types of background agents: periodic agents that run every 30 minutes and resource intensive agents that run when the phone is charging.
2) Background agents have limited access to phone resources and can only run for a maximum of 25 seconds for periodic agents and 10 minutes for resource intensive agents.
3) The document provides examples of using background agents to perform periodic location tracking, file transfers, and audio playback even when the main application is not active.
in last Seven Peaks Speaks android webinar: How to code effectively with MAD, Fedor talked about Background Processing with Work Manager, where we will learn about the best practices for scheduling one-time and periodic background work with Jetpack Work Manager.
Threads handlers and async task, widgets - day8Utkarsh Mankad
This document discusses processes and threads in Android, process lifecycles, thread management principles, and how to create and manage widgets in Android. It covers the following key points:
- Processes and threads in Android and how the main thread handles UI events.
- The 5 levels of importance for application processes and when processes are killed.
- Using handlers and AsyncTasks to perform background work without blocking the UI thread.
- The basics of widgets including the AppWidgetProviderInfo, AppWidgetProvider class, and layout.
- The steps to create a widget including declaring it in the manifest, metadata, layouts, provider class, and configuration activity.
This document discusses various background processing techniques in Android including services, threads, AsyncTask, IntentService, JobScheduler, AlarmManager, ContentProvider, and DownloadManager. It provides examples of when to use each technique and considerations around restarting services, binding, and syncing.
The document summarizes new features in Android M, including changes to app permissions where users can now revoke permissions after install instead of granting all upfront, a new fingerprint API, Doze and App Standby modes for improved battery life, Assistant support to provide context about app screens, and data binding, material design libraries, App Links, and Direct Share. The presentation was given by Amrit Sanjeev from the organization Blrdroid on introducing developers to the top 10 things in Android M.
Running Code in the Android Stack at ABS 2014Opersys inc.
This document provides an overview of running code in the Android stack, covering various topics:
1) It discusses the different programming languages and components used to build Android applications and the platform itself, including Java, C/C++, and various Android app components.
2) It outlines standard app mechanisms like intents, components, processes and threads that apps use to integrate with the Android system.
3) It briefly covers some special app mechanisms like services, content providers and widgets.
Android N 7.0 introduces many new features for developers including multi-window support, notifications improvements, compiler changes using Jack and Jill, and enhancements to Doze battery optimizations. The presentation focuses on explaining the hybrid JIT/AOT compilation approach in Android N, changes to the Android runtime moving away from Dalvik to ART, impacts of multiprocess WebView, and how to test applications against Doze restrictions.
David Marques gave a presentation on Android app development to a user group in São Paulo, Brazil. He began by introducing himself and his background in mobile development. The presentation covered the core components of Android apps including activities, services, content providers, and intent receivers. Marques explained how each component works and provided code examples. He emphasized doing background work in services on separate threads to avoid blocking the main thread.
Android Lollipop internals and inferiority complex droidcon.hr 2015 Aleksander Piotrowski
Presentation from droidcon Zagreb 2015
While going through JobScheduler internals try to answer the following question: How big is the gap between us and rockstar developers from Google or Square
Android Lollipop internals and inferiority complex droidcon.hr 2015
Job schedulers android
1. Job Schedulers in Android
By Deesha Vora (@Deesharv)
Co-founder & Chief of Product @SuperWiseSite
Email: deesha@superwise.site
2. What’s JobScheduler ?
Job Service
The work you are
wanting to do.
Extends Job Service
class. Job runs on main
thread.
Need to implement
● onStartJob()
● jobFinished()
Job Info
Job Info object is
conditions under which
Job service will execute.
Need to Give
● JobID
● JobService
● Criteria(s) for
trigger.
[Network, Charging/Idle,
Content URI (API 24),
Backoff-Policy, Periodic]
Job Scheduler
Job Scheduler is used to
schedule the job.
schedule() call using
JobInfo object and Job
with similar ID will be
replaced.
3.
4. JOB SERVICE
public class MyJobService extends JobService {
boolean isWorking = false;
boolean jobCancelled = false;
// Called by the Android system when it's time to run the job
@Override
public boolean onStartJob(JobParameters jobParameters) {
Log.d(“TAG”, "Job started!");
isWorking = true;
startWorkOnNewThread(jobParameters);
5. JOB SERVICE
// Services do NOT run on a separate thread
return isWorking;
}
private void startWorkOnNewThread(final JobParameters jobParameters) {
new Thread(new Runnable() {
public void run() {
doWork(jobParameters);
}
}).start(); }
6. JOB SERVICE
private void doWork(JobParameters jobParameters) {
// 10 seconds of working (1000*10ms)
for (int i = 0; i < 1000; i++) {
// If the job has been cancelled, stop working; the job will be rescheduled.
if (jobCancelled)
return;
try { Thread.sleep(10); } catch (Exception e) { }
}
Log.d(TAG, "Job finished!");
isWorking = false;
boolean needsReschedule = false;
jobFinished(jobParameters, needsReschedule);
}
7. JOB SERVICE
// Called if the job was cancelled before being finished
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d(TAG, "Job cancelled before being completed.");
jobCancelled = true;
boolean needsReschedule = isWorking;
jobFinished(jobParameters, needsReschedule);
return needsReschedule;
} }
8. JOB SERVICE to MANIFEST
<service
android:name=".MyJobService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
9. SET UP JOB INFO
ComponentName componentName = new ComponentName(this,
MyJobService.class);
JobInfo jobInfo = new JobInfo.Builder(12, componentName)
.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.build();
10. Time to Schedule
JobScheduler jobScheduler =
(JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled!");
} else {
Log.d(TAG, "Job not scheduled");
}
11. Intelligent Jon-
Schedulers
Scheduling this work intelligently can
improve your app’s performance
Note: Use Handler if app is in
foreground
AlarmManager
GCM Network Manager
Firebase JobDispatcher
SyncAdapter
Services
12. Alarm Manger
● We should only use AlarmManager API for tasks that must execute at a
specific time or after specific time.
● This does not provide more robust execution conditions like device is idle,
network is available or charging detect.
13. GCM Network Manager
● Has all the schedule features from JobScheduler.
● Can also use below Android 5.0 (API level 21). From API level 23 or higher, GCM
Network Manager uses the framework’s JobScheduler.
● Uses the scheduling engine inside Google Play services
● Google has strongly recommended for GCM users to upgrade to FCM and
instead use Firebase Job Dispatcher for scheduling any tasks.
14. Firebase Job Dispatcher
● supports backward compatibility (below API 21) & works on all recent versions
of Android (API 9+).
● If device do not have Google play services installed , this library internally uses
AlarmManager. If Google Play service is available on the device then it uses the
scheduling engine inside Google Play services.
● It uses AlarmManager to support API levels <= 21 if Google Play services is
unavailable. For the device running on API level 21, it uses JobScheduler
15. Sync Adapter
● Sync adapters are designed specifically for syncing data between a device and
the cloud.
● 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
● 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.
16. DOZE & APP Stand by restrictions
● The system ignores wake locks.
● The system does not allow sync adapters to run.
● The system does not allow JobScheduler to run
● Standard AlarmManager alarms (including setExact() and setWindow()) are
deferred to the next maintenance window.
○ The system does not perform Wi-Fi scans.
● Network access is suspended.
17. DOZE & APP Standby solutions
Alarm Manger
● API 23 introduces two new AlarmManager methods: setAndAllowWhileIdle()
and setExactAndAllowWhileIdle().
If the device is idle for long periods of time, the system allows idle apps network
access around once a day
● Whitelist request for the app, to allow partial wake lock
● Acceptable whitelist cases
18. Data cost sensitivity Job-Schedulers in Android P
● With Android P, JobScheduler has been improved to let it better handle
network-related jobs for the user, in coordination with network status signals
provided separately by carriers.
● Jobs can now declare their estimated data size, signal prefetching, and specify
detailed network requirements—carriers can report networks as being
congested or unmetered.
19. Data cost sensitivity …
● When adding jobs, make sure to use setEstimatedNetworkBytes(),
setIsPrefetch(), and setRequiredNetwork()
● When your job executes, be sure to use the Network object returned by
JobParameters.getNetwork()
20. Thank you !
By Deesha Vora (@Deesharv)
Co-founder & Chief of Product @SuperWiseSite
Email: deesha@superwise.site
Job-Scheduler libraries
https://github.com/evernote/android-job
https://github.com/yigit/android-priority-jobqueue
Editor's Notes
Advantage of JoScheduler -
1. Dont worry for the result, JobScheduler will Retry and Reshedule your Job
2. Jobs will be batched if the creitira is similar like Network
3. App will be Doze aware
4. Minimum latency and override deadline
5. Periodic
6. Persistent
7. Extras
8. You can schedule a job using JobScheduler, which you will retrieve from the system. Then, call schedule() using your JobInfo object, and you are good to go. No worries needed.
public class MyJobService extends JobService {
private static final String TAG = MyJobService.class.getSimpleName();
boolean isWorking = false;
boolean jobCancelled = false;
// Called by the Android system when it's time to run the job
@Override
public boolean onStartJob(JobParameters jobParameters) {
Log.d(TAG, "Job started!");
isWorking = true;
// We need 'jobParameters' so we can call 'jobFinished'
startWorkOnNewThread(jobParameters); // Services do NOT run on a separate thread
return isWorking;
}
private void startWorkOnNewThread(final JobParameters jobParameters) {
new Thread(new Runnable() {
public void run() {
doWork(jobParameters);
}
}).start();
}
private void doWork(JobParameters jobParameters) {
// 10 seconds of working (1000*10ms)
for (int i = 0; i < 1000; i++) {
// If the job has been cancelled, stop working; the job will be rescheduled.
if (jobCancelled)
return;
try { Thread.sleep(10); } catch (Exception e) { }
}
Log.d(TAG, "Job finished!");
isWorking = false;
boolean needsReschedule = false;
jobFinished(jobParameters, needsReschedule);
}
// Called if the job was cancelled before being finished
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d(TAG, "Job cancelled before being completed.");
jobCancelled = true;
boolean needsReschedule = isWorking;
jobFinished(jobParameters, needsReschedule);
return needsReschedule;
}
}
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.
to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
The framework continues to provide the SyncAdapter class for managing tasks that sync data between the device and a server. Sync adapters are designed specifically for syncing data between a device and the cloud; you should only use them for this type of task. Sync adapters are more complex to implement than the libraries and APIs mentioned above, because they require at least a fake authenticator and content provider implementation. For these reasons, you typically should not create a sync adapter just to sync data to the cloud in the background. Wherever possible, you should instead 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.
SERVICES:
The Services framework allows you to perform long-running operations in the background. We recommend foreground services for tasks, such as playing music, which need to stay resident for the user. Bound services also continue to be useful for various use cases: for example, when a service needs to run only when a user is viewing a fragment or activity.
You should avoid using started services that run perpetually or perform periodic work, since they continue to use device resources even when they are not performing useful tasks. Instead, you should use other solutions that this page describes, and that provide native lifecycle management. Use started services only as a last resort. The Android platform may not support started services in the future.
Captive Internet Portals, VPNs, and proxies can pose Internet-connectivity detection problems. A library or API may think the Internet is available, but your service may not be accessible. Fail gracefully and reschedule as few of your tasks as possible.
Depending on the conditions you assign for running a task, such as network availability, after the task is triggered, a change may occur so that those conditions are no longer met. In such a case, your operation may fail unexpectedly and repeatedly. For this reason, you should code your background task logic to notice when tasks are failing persistently, and perform exponential back-off to avoid inadvertently over-using resources.
Remember to use exponential backoff when rescheduling any work, especially when using AlarmManager. If your app uses JobScheduler, Firebase JobDispatcher, or sync adapters, exponential backoff is automatically used.
https://android.jlelse.eu/schedule-tasks-and-jobs-intelligently-in-android-e0b0d9201777
Use
Doze is particularly likely to affect activities that AlarmManager alarms and timers manage, because alarms in Android 5.1 (API level 22) or lower do not fire when the system is in Doze.
To help with scheduling alarms, Android 6.0 (API level 23) introduces two new AlarmManagermethods: setAndAllowWhileIdle() and setExactAndAllowWhileIdle(). With these methods, you can set alarms that will fire even if the device is in Doze.
Note: Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire alarms more than once per 9 minutes, per app.
App Standby allows the system to determine that an app is idle when the user is not actively using it. The system makes this determination when the user does not touch the app for a certain period of time and none of the following conditions applies:
The user explicitly launches the app.
The app has a process currently in the foreground (either as an activity or foreground service, or in use by another activity or foreground service).
Note: You should only use a foreground service for tasks the user expects the system to execute immediately or without interruption. Such cases include uploading a photo to social media, or playing music even while the music-player app is not in the foreground. You should not start a foreground service simply to prevent the system from determining that your app is idle.
The app generates a notification that users see on the lock screen or in the notification tray.
The app is an active device admin app (for example, a device policy controller). Although they generally run in the background, device admin apps never enter App Standby because they must remain available to receive policy from a server at any time.
When the user plugs the device into a power supply, the system releases apps from the standby state, allowing them to freely access the network and to execute any pending jobs and syncs. If the device is idle for long periods of time, the system allows idle apps network access around once a day.
GCM Network Manager is also meant for performing repeated or one-off, non-imminent work while keeping battery life in mind.
so this class will only work if the Google Play services is installed on the device.
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.
Tip: It uses AlarmManager to support API levels <= 21 if Google Play services is unavailable.
For the device running on API level 21, it uses JobScheduler. This library also has the same framework so there is no change in functionality.
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.
The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component. To add a sync adapter component to your app, you need to add the following pieces:
Sync adapter class.
A class that wraps your data transfer code in an interface compatible with the sync adapter framework.
Bound Service.
A component that allows the sync adapter framework to run the code in your sync adapter class.
Sync adapter XML metadata file.
A file containing information about your sync adapter. The framework reads this file to find out how to load and schedule your data transfer.
Declarations in the app manifest.
XML that declares the bound service and points to sync adapter-specific metadata.
This lesson shows you how to define these elements.
https://android.jlelse.eu/schedule-tasks-and-jobs-intelligently-in-android-e0b0d9201777
If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().
Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.
Doze is particularly likely to affect activities that AlarmManager alarms and timers manage, because alarms in Android 5.1 (API level 22) or lower do not fire when the system is in Doze.
To help with scheduling alarms, Android 6.0 (API level 23) introduces two new AlarmManagermethods: setAndAllowWhileIdle() and setExactAndAllowWhileIdle(). With these methods, you can set alarms that will fire even if the device is in Doze.
Note: Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire alarms more than once per 9 minutes, per app.
App Standby allows the system to determine that an app is idle when the user is not actively using it. The system makes this determination when the user does not touch the app for a certain period of time and none of the following conditions applies:
The user explicitly launches the app.
The app has a process currently in the foreground (either as an activity or foreground service, or in use by another activity or foreground service).
Note: You should only use a foreground service for tasks the user expects the system to execute immediately or without interruption. Such cases include uploading a photo to social media, or playing music even while the music-player app is not in the foreground. You should not start a foreground service simply to prevent the system from determining that your app is idle.
The app generates a notification that users see on the lock screen or in the notification tray.
The app is an active device admin app (for example, a device policy controller). Although they generally run in the background, device admin apps never enter App Standby because they must remain available to receive policy from a server at any time.
When the user plugs the device into a power supply, the system releases apps from the standby state, allowing them to freely access the network and to execute any pending jobs and syncs. If the device is idle for long periods of time, the system allows idle apps network access around once a day.
https://android.jlelse.eu/schedule-tasks-and-jobs-intelligently-in-android-e0b0d9201777
Doze is particularly likely to affect activities that AlarmManager alarms and timers manage, because alarms in Android 5.1 (API level 22) or lower do not fire when the system is in Doze.
To help with scheduling alarms, Android 6.0 (API level 23) introduces two new AlarmManagermethods: setAndAllowWhileIdle() and setExactAndAllowWhileIdle(). With these methods, you can set alarms that will fire even if the device is in Doze.
Note: Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire alarms more than once per 9 minutes, per app.
App Standby allows the system to determine that an app is idle when the user is not actively using it. The system makes this determination when the user does not touch the app for a certain period of time and none of the following conditions applies:
The user explicitly launches the app.
The app has a process currently in the foreground (either as an activity or foreground service, or in use by another activity or foreground service).
Note: You should only use a foreground service for tasks the user expects the system to execute immediately or without interruption. Such cases include uploading a photo to social media, or playing music even while the music-player app is not in the foreground. You should not start a foreground service simply to prevent the system from determining that your app is idle.
The app generates a notification that users see on the lock screen or in the notification tray.
The app is an active device admin app (for example, a device policy controller). Although they generally run in the background, device admin apps never enter App Standby because they must remain available to receive policy from a server at any time.
When the user plugs the device into a power supply, the system releases apps from the standby state, allowing them to freely access the network and to execute any pending jobs and syncs. If the device is idle for long periods of time, the system allows idle apps network access around once a day.
Users can manually configure the whitelist in Settings > Battery > Battery Optimization. Alternatively, the system provides ways for apps to ask users to whitelist them.
An app can fire the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent to take the user directly to the Battery Optimization, where they can add the app.
An app holding the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission can trigger a system dialog to let the user add the app to the whitelist directly, without going to settings. The app fires a ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent to trigger the dialog.
The user can manually remove apps from the whitelist as needed.