droidcon Transylvania - Kotlin CoroutinesArthur Nagy
We face challenges with threading on a daily basis. There are too many ways to do it, too many options. Do I use an AsyncTaks, a Runnable or RxJava, what do I do? All these available APIs lead to an almost inevitable callback hell.
This talk will introduce Kotlin Coroutines as an alternative solution to this problem. We’re going to explore simple ways to perform long-running tasks and computation heavy operations in an asynchronous way, without freezing or crashing your app, while keeping the code clean and readable at the same time.
What is a Coroutine in Kotlin? Which are the differences with threads? What is collaborative concurrency? Have a look at these slides and at the companion Github repository https://github.com/f-lombardo/kotlin-from-scratch
droidcon Transylvania - Kotlin CoroutinesArthur Nagy
We face challenges with threading on a daily basis. There are too many ways to do it, too many options. Do I use an AsyncTaks, a Runnable or RxJava, what do I do? All these available APIs lead to an almost inevitable callback hell.
This talk will introduce Kotlin Coroutines as an alternative solution to this problem. We’re going to explore simple ways to perform long-running tasks and computation heavy operations in an asynchronous way, without freezing or crashing your app, while keeping the code clean and readable at the same time.
What is a Coroutine in Kotlin? Which are the differences with threads? What is collaborative concurrency? Have a look at these slides and at the companion Github repository https://github.com/f-lombardo/kotlin-from-scratch
Azul Virtual Machine Engineer Douglas Hawkins describes how decisions made by the JVM affect how your code is compiled and run. Learn how this affects application performance and what steps you can take to optimize how the JVM acts on your code.
Physical Web is an important component for the Smart Cities and for monetizing IoT projects. This talk explain what is it and how to implement it using Eddystone protocol.
JavaFX 8 est disponible depuis mars 2014 et apporte son lot de nouveautés. Gradle est en version 2 depuis juillet 2014. Deux technologies plus que prometteuses: JavaFX donne un coup de jeune au développement d’applications desktop en Java en apportant un navigateur web intégré, le support des WebSockets, de la 3D, et bien d’autres. Gradle est l’outil de d’automatisation de build à la mode, apportant de superbes possibilités par rapport rapport à maven, outil vieillissant, grâce à l’engouement de la communauté vis à vis de cet outil mais aussi par le fait de la technologie utilisée en son sein: groovy. Venez découvrir comment il est possible de réaliser rapidement une application à la mode en JavaFX avec un outil à la mode également. Bref venez à une session trendy.
Aplicações assíncronas no Android com Coroutines & JetpackNelson Glauber Leal
Para usufruir dos múltiplos núcleos existentes nos processadores dos smartphones atuais, podemos realizar chamadas assíncronas de modo a paralelizar o fluxo de execução da aplicação. Normalmente isso é feito por meio de threads e callbacks que acabam por adicionar uma complexidade ao código que pode comprometer sua leitura e manutenção. Nessa apresentação, veremos como utilizar a API de Coroutines do Kotlin em conjunto com diversas bibliotecas do Jetpack do Android de modo a implementar programação assíncrona forma simples e eficiente.
There is hardly a Senior Java developer who has never heard of sun.misc.Unsafe. Though it has always been a private API intended for JDK internal use only, the popularity of Unsafe has grown too fast, and now it is used in many open-source projects. OK.RU is not an exception: its software also heavily relies on Unsafe APIs.
During this session we'll try to understand what is so attractive about Unsafe. Why do people keep using it regardless the warnings of removal from future JDK releases? Are there any safe alternatives to private API or is it absolutely vital? We will review the typical cases when Java developers prefer to go unsafe and discuss major benefits and the drawbacks of it. The report will be supported by the real examples from OK.RU experience.
Azul Virtual Machine Engineer Douglas Hawkins describes how decisions made by the JVM affect how your code is compiled and run. Learn how this affects application performance and what steps you can take to optimize how the JVM acts on your code.
Physical Web is an important component for the Smart Cities and for monetizing IoT projects. This talk explain what is it and how to implement it using Eddystone protocol.
JavaFX 8 est disponible depuis mars 2014 et apporte son lot de nouveautés. Gradle est en version 2 depuis juillet 2014. Deux technologies plus que prometteuses: JavaFX donne un coup de jeune au développement d’applications desktop en Java en apportant un navigateur web intégré, le support des WebSockets, de la 3D, et bien d’autres. Gradle est l’outil de d’automatisation de build à la mode, apportant de superbes possibilités par rapport rapport à maven, outil vieillissant, grâce à l’engouement de la communauté vis à vis de cet outil mais aussi par le fait de la technologie utilisée en son sein: groovy. Venez découvrir comment il est possible de réaliser rapidement une application à la mode en JavaFX avec un outil à la mode également. Bref venez à une session trendy.
Aplicações assíncronas no Android com Coroutines & JetpackNelson Glauber Leal
Para usufruir dos múltiplos núcleos existentes nos processadores dos smartphones atuais, podemos realizar chamadas assíncronas de modo a paralelizar o fluxo de execução da aplicação. Normalmente isso é feito por meio de threads e callbacks que acabam por adicionar uma complexidade ao código que pode comprometer sua leitura e manutenção. Nessa apresentação, veremos como utilizar a API de Coroutines do Kotlin em conjunto com diversas bibliotecas do Jetpack do Android de modo a implementar programação assíncrona forma simples e eficiente.
There is hardly a Senior Java developer who has never heard of sun.misc.Unsafe. Though it has always been a private API intended for JDK internal use only, the popularity of Unsafe has grown too fast, and now it is used in many open-source projects. OK.RU is not an exception: its software also heavily relies on Unsafe APIs.
During this session we'll try to understand what is so attractive about Unsafe. Why do people keep using it regardless the warnings of removal from future JDK releases? Are there any safe alternatives to private API or is it absolutely vital? We will review the typical cases when Java developers prefer to go unsafe and discuss major benefits and the drawbacks of it. The report will be supported by the real examples from OK.RU experience.
Andrew Betts Web Developer, The Financial Times at Fastly Altitude 2016
Running custom code at the Edge using a standard language is one of the biggest advantages of working with Fastly’s CDN. Andrew gives you a tour of all the problems the Financial Times and Nikkei solve in VCL and how their solutions work.
Things fail. It’s a fact of life. But that doesn’t mean that your applications and services need to fail. In this talk, David Prinzing described a solution architecture that has been proven to deliver amazing performance at scale with continuous availability on Amazon Web Services. You can’t just move your application to the cloud and expect this – you need to design for it. Technology selections include Amazon Web Services, Ubuntu Linux, Apache Cassandra for the database, Dropwizard for providing RESTful web services, and AngularJS as the foundation for an HTML5 web application. Event: http://www.meetup.com/AWS-EASTBAY/events/225570266
"Swoole: double troubles in c", Alexandr VronskiyFwdays
Practices in using Swoole ecosystem & migration real production marketplace app to async approach. Which benefits we got and what problems happens on stack with PHP8, Postgresql, Redis, RebbitMQ, Doctrine, coroutines/fibers, concurrency HTTP Server.
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingIstanbul Tech Talks
Android is now the most popular software platform in the world and millions of people use it in their everyday life. One of the largest challenges for application developers is how to make their applications consume as little network and battery as possible. Although the Android platform has improved a lot over the years, there are still lots of things that developers need to think about. In this session, Erik goes through the different choices and what they will mean to your application. Learn about the latest protocols, Android platform tricks and how to get the most out of an Android device without draining its battery.
This presentation aggregates common approaches of real-time client-server communications provided by Web Standards. It focuses on comparison of different techniques like polling, comet, Web Sockets, Server-Sent Events.
HTTP is one of the most widely used protocols in the world.
The version of HTTP 1.1, used to this day, was developed and described 18 years ago - 1999.
With the increasing complexity of web applications, the capabilities of HTTP 1.1 are already insufficient to provide increased demands on performance and responsiveness.
So in order to meet new requirements, HTTP must evolve. HTTP 2.0 is designed to make web applications faster, simple and reliable.
In this report I will tell about
- drawbacks of HTTP 1.1 and why we need a new version of HTTP.
- which advantages HTTP/2 offers in comparison with the previous version?
- how the new protocol affected the new version of SERVLET 4.0 and how we can use it.
Doze mode is just around the corner. Introduced in Marshmallow, as the shy guy that was allowed to step in only when your device went to sleep. ZzzZzzzz With the new N release, Doze mode becomes the rockstar. He rushes into the room with a big shabang by shooting all background services and network requests that forgot to get away. He should no longer be shy. He just shoots and dances on bones of your scheduled alarms, while you wonder why this particular task is no longer running. With the new Doze mode, you require to adapt your app architecture to the new reality. On this talk, we will learn how to survive Doze mode using Job Scheduler and stay in one piece.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
17. Common errors
- Polling chat/message from server every 5 seconds even when
app in the background
- Pulling photos/articles from server every time user opens the
Gallery even when nothing is changed
- Retrying failing networking requests till them will succeed.
- Service that never stops...
- A lot of bugs :)
32. ● Hypertext Transfer Protocol.
● This makes HTTP a stateless protocol. The communication
usually takes place over TCP/IP, but any reliable transport can be
used. The default port for TCP/IP is 80, but other ports can also
be used.
HTTP
33. URL
The protocol is typically http, but it can also be https for secure
communications.
34. HTTP Verb
Specifying the action we want to perform on host
● GET: fetch an existing resource. The URL contains all the necessary
information the server needs to locate and return the resource.
● POST: create a new resource. POST requests usually carry a payload that
specifies the data for the new resource.
● PUT: update an existing resource. The payload may contain the updated data
for the resource.
● DELETE: delete an existing resource.
35. Status Code
In return, the server responds with status codes and message payloads
1xx: Informational Messages - Expect: 100-continue
2xx: Successful - 200 OK, 204 No Content
3xx: Redirection - This requires the client to take additional action. The most
common use-case is to jump to a different URL in order to fetch the resource.
4xx: Client Error - 404 Not Found, 400 Bad Request,401 Unauthorized,
5xx: Server Error - 503 Service Unavailable
41. HTTP & HTTPS
A TCP stream is broken into IP packets, and it ensures that those
packets always arrive in the correct order without fail. HTTP is an
application layer protocol over TCP, which is over IP.
45. Parallel connections
If there are six assets that the client needs to download from a
website, the client makes six parallel connections to download those
assets, resulting in a faster turnaround.
47. Server side
● establishing a socket to start listening on port 80 (or some other port)
● receiving the request and parsing the message
● processing the response
● setting response headers
● sending the response to the client
● close the connection if a Connection: close request header was found
59. public interface UserService {
@POST("me")
Call<User>me();
}
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/v2/");
.build();
UserService service = retrofit.create(UserService.class);
// the request url for service.me() is:
// https://your.api.url/v2/me
60. OkHttp Integrated
Retrofit 2 relies on OkHttp as the HTTP client and has its own dependency to the
library as well
compile 'com.squareup.okhttp3:okhttp:3.3.1'
OkHttpClient client = httpClient.build();
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/v2/");
.client(client)
.build();
69. Multiple Convertors
First come - first server
First fail, pass to next ne
One that succeed - consume the response.
Add the esoteric first and more general like GSON last.
81. What is it and how i eat that
Android Framework
API >= 7 (Android 2.1)
Synchronizing data between an Android device and web servers
You specify what you should sync , how often - and it will do the rest
83. Let’s compare
Custom Sync Sync Adapter
Network Availability - manually Network Availability - Automatically
Pending Queue - manually Pending Queue - Automatically
Refresh on Network - manually Refresh on Network - Automatically
Periodic Update - manually Periodic Update - Automatically
Sync Setting - manually Sync Setting - Automatically
Network Bandwidth - manually Network Bandwidth - Automatically
Battery Efficient - ?? Depend on you Battery Efficient - Yes
Survive on Reboot - Depends on you Survive on Reboot - Yes
84.
85. How to?
Sqlite Database: I guess you all are master of Sqlite database, SyncAdapter will store data in
Sqlite using Content Provider. You may choose other options as well.
Content Provider: Act as bridge between your database and SyncAdapter. To expose your
data in Rest like URL pattern.
AbstractAccountAuthenticator: We need to extend this class and override methods, It is
primarily used to manage authentication and account management. To use SyncAdapter you
must have custom account. This class is responsible to create account, maintain auth token.
86. How to?
Authenticator Service: This is normal Service, which we are using daily. The only difference
is that this service create object of AbstractAccountAuthenticator class and bind.
AbstractThreadedSyncAdapter: As developer we need to extend this class and override
methods. This is the main piece of SyncAdapter puzzle. It has method onPerformSync, in
which we need to write our code.
Sync Service: This is normal Service. It use to create object of
AbstractThreadedSyncAdapter class and bind.
87. How to?
Authenticator.xml: You need to create this file under res/xml/ folder. This file is required to bind your
authenticator component into the sync adapter and account frameworks, you need to provide these framework
with metadata that describes the component. You can choose your own file name.
SyncAdapter.xml: You need to create this file under res/xml/ folder. The metadata specifies the account type
you've created for your sync adapter, declares a content provider authority associated with your app.
AndroidManifest.xml: You must register Sync Service, Authenticator service and few other things in
AndroidManifast file in order to work SyncAdapter, This is the final piece of puzzle.
90. What?
Schedule the task to execute it when certain conditions met.
(charging, idle, connected to a network or connected to an unmetered
network)
91. Why two?
JobScheduler was introduced in API >= 21 (Lollipop).
GCMNetworkManager - is part of GCM package. When using on
devices >= 21, use JobScheduler underneath.
95. BestTimeService.java
/**
* Task run by GcmNetworkManager when all the requirements of the scheduled
* task are met.
*/
public class BestTimeService extends GcmTaskService {
...
}
96. BestTimeService.java
@Override
public int onRunTask(TaskParams taskParams) {
Log.i(TAG, "onRunTask");
switch (taskParams.getTag()) {
case TAG_TASK_ONEOFF_LOG:
Log.i(TAG, TAG_TASK_ONEOFF_LOG);
// This is where useful work would go
return GcmNetworkManager.RESULT_SUCCESS;
case TAG_TASK_PERIODIC_LOG:
Log.i(TAG, TAG_TASK_PERIODIC_LOG);
// This is where useful work would go
return GcmNetworkManager.RESULT_SUCCESS;
default:
return GcmNetworkManager.RESULT_FAILURE;
}
}
98. Scheduling a task
Task task = new OneoffTask.Builder()
.setService(BestTimeService.class)
.setExecutionWindow(0, 30)
.setTag(BestTimeService.TAG_TASK_ONEOFF_LOG)
.setUpdateCurrent(false)
.setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
.setRequiresCharging(false)
.build();
mGcmNetworkManager.schedule(task);
99. What’s in it?
● Service: The specific GcmTaskService that will control the task.
This will allow us to cancel it later.
● Execution window: The time period in which the task will execute.
First param is the lower bound and the second is the upper bound
(both are in seconds). This one is mandatory.
● Tag: We’ll use the tag to identify in the onRunTask method which
task is currently being run. Each tag should be unique, and the
max length is 100.
100. What’s in it?
● Update Current: This determines whether this task should
override any pre-existing tasks with the same tag. By default, this
is false, so new tasks don’t override existing ones.
● Required Network: Sets a specific network state to run on. If that
network state is unavailable, then the task won’t be executed until
it becomes available.
● Requires Charging: Whether the task requires the device to be
connected to power in order to execute.
101. Scheduling a periodic task
Task task = new PeriodicTask.Builder()
.setService(BestTimeService.class)
.setPeriod(30)
.setFlex(10)
.setTag(BestTimeService.TAG_TASK_PERIODIC_LOG)
.setPersisted(true)
.build();
mGcmNetworkManager.schedule(task);
102. What’s in it?
● Period: Specifies that the task should recur once every interval at
most, where the interval is the input param in seconds. By
default, you have no control over where in that period the task will
execute. This setter is mandatory.
● Flex: Specifies how close to the end of the period (set above) the
task may execute. With a period of 30 seconds and a flex of 10,
the scheduler will execute the task between the 20-30 second
range.
103. What’s in it?
● Persisted: Determines whether the task should be persisted
across reboots. Defaults to true for periodic tasks, and is not
supported for one-off tasks. Requires “Receive Boot Completed”
permission, or the setter will be ignored.
107. Not all devices shipped with Play Services
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode == ConnectionResult.SUCCESS) {
mGcmNetworkManager.schedule(task);
} else {
// Deal with this networking task some other way
}
108. When Google Play updated it removes all scheduled periodic tasks
public class BestTimeService extends GcmTaskService {
@Override
public void onInitializeTasks() {
super.onInitializeTasks();
// Reschedule removed tasks here
}
}
126. Message strategy
● Notifications delivered when your app is in the background. In this case, the
notification is delivered to the device’s system tray. A user tap on a
notification opens the app launcher by default.
● Messages with both notification and data payload. In this case, the notification
is delivered to the device’s system tray, and the data payload is delivered in
the extras of the intent of your launcher Activity.
127. public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
sendNotification(remoteMessage.getNotification().getBody());
}
}
MyFirebaseMessagingService
144. WhiteList
● An app can fire the
ACTION_IGNORE_BATTERY_OPTIMIZATION_SE
TTINGS 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
145. WhiteList
● 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_OPTIMIZ
ATIONS Intent to trigger the dialog.
146. Note: Google Play policies prohibit apps from
requesting direct exemption from Power
Management features in Android 6.0+ (Doze
and App Standby) unless the core function of
the app is adversely affected.
154. Process
1. Create schema
2. Compile schema with flatc compiler
3. Import generated files into your project
4. Read from byte[]:
java.nio.ByteBuffer buf = builder.dataBuffer();
// Deserialize the data from the buffer.
StarWars starWars = StarWars.getRootAsStarWars(buf);