This document describes how we can break a long running background task in an Android service into different states and how we can notify the UI about these states as they proceed.,
Scaling Ruby with Evented I/O - Ruby undergroundOmer Gazit
Ruby is considered by many to be slow and unscalable. In this talk we’ll try to disprove this premise by introducing EventMachine. We will cover the basic concepts of evented I/O programming and the Reactor pattern. Talk about best practices and useful libraries for EventMachine and see how to test your event driven code.
Code examples from the presentation can be found at: https://github.com/omerisimo/em_underground
Tornado is a non-blocking light-weight web server and framework. There's been many introductory talks about it, and it's time to look deeper into it: not just what Tornado does, but how it does it and what can we learn from it when designing our own concurrent systems.
In this talk I go over the following topics. I cover them in two parts: first I present how to use a certain feature or approach in our applications; then, I dig into Tornado's source code to see how it really works.
- Getting Started: quickly get a simple Tornado application up and running. We'll keep digging into, changing and poking this Application for most of the talk.
- An Application Listens: what an Application is, how does Tornado start it and how does it process its requests.
- Application and IOLoop: we'll look at how the IOLoop receives the connections from the users and passes them on to the Applications.
- Scheduled Tasks: we'll see how to schedule tasks and how the IOLoop will run them.
- Generators: we'll learn to use generators to handle the responses of our asynchronous calls, and how they work with the IOLoop.
Advanced:
- Websockets: how to use them and how they work.
- IOStream: how do Tornado's non-blocking sockets work.
- Database: how to use non-blocking sockets to connect to databases.
- Process: how Tornado works with multiple processes.
I presented this talk at Europython 2012 and PyGrunn 2012.
Code examples: https://bitbucket.org/grimborg/tornado-in-depth/src/tip/examples/
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
Puppet is a configuration management utility that can be used to provision environments rapidly. This Ignite Talk describes some of the concepts behind Puppet.
Scaling Ruby with Evented I/O - Ruby undergroundOmer Gazit
Ruby is considered by many to be slow and unscalable. In this talk we’ll try to disprove this premise by introducing EventMachine. We will cover the basic concepts of evented I/O programming and the Reactor pattern. Talk about best practices and useful libraries for EventMachine and see how to test your event driven code.
Code examples from the presentation can be found at: https://github.com/omerisimo/em_underground
Tornado is a non-blocking light-weight web server and framework. There's been many introductory talks about it, and it's time to look deeper into it: not just what Tornado does, but how it does it and what can we learn from it when designing our own concurrent systems.
In this talk I go over the following topics. I cover them in two parts: first I present how to use a certain feature or approach in our applications; then, I dig into Tornado's source code to see how it really works.
- Getting Started: quickly get a simple Tornado application up and running. We'll keep digging into, changing and poking this Application for most of the talk.
- An Application Listens: what an Application is, how does Tornado start it and how does it process its requests.
- Application and IOLoop: we'll look at how the IOLoop receives the connections from the users and passes them on to the Applications.
- Scheduled Tasks: we'll see how to schedule tasks and how the IOLoop will run them.
- Generators: we'll learn to use generators to handle the responses of our asynchronous calls, and how they work with the IOLoop.
Advanced:
- Websockets: how to use them and how they work.
- IOStream: how do Tornado's non-blocking sockets work.
- Database: how to use non-blocking sockets to connect to databases.
- Process: how Tornado works with multiple processes.
I presented this talk at Europython 2012 and PyGrunn 2012.
Code examples: https://bitbucket.org/grimborg/tornado-in-depth/src/tip/examples/
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
Puppet is a configuration management utility that can be used to provision environments rapidly. This Ignite Talk describes some of the concepts behind Puppet.
No Callbacks, No Threads - RailsConf 2010Ilya Grigorik
Multi-threaded servers compete for the global interpreter lock (GIL) and incur the cost of continuous context switching, potential deadlocks, or plain wasted cycles. Asynchronous servers, on the other hand, create a mess of callbacks and errbacks, complicating the code. But, what if, you could get all the benefits of asynchronous programming, while preserving the synchronous look and feel of the code – no threads, no callbacks?
Domains were added to Node.js in 0.8, but their use and workings have been a relative mystery. In short, domains are a structured way of reacting to uncaught exceptions; for example, when creating an HTTP server, you can use domains to send 500 errors when exceptions occur instead of crashing your server. This talk will go over what domains are, how to use them, and some of the subtleties behind how they work.
Droidcon Berlin 2021 - With coroutines being the de facto way of exposing async work and streams of changes for Kotlin on Android, developers are obviously attempting to use the same approaches when moving their code to Multiplatform.
But due to the way the memory model differs between JVM and Kotlin Native, it can be a painful experience.
In this talk, we will take a deep dive into the Coroutine API for Kotlin Multiplatform. You will learn how to expose your API with Coroutines while working with the Kotlin Native memory model instead of against it, and avoid the dragons along the way.
An attempt to see how node is faster than (PHP+Acpache) stack where situations are similar and none of them are tweaked from their default configuration
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...GeeksLab Odessa
23.05.15 Одесса. Impact Hub Odessa. Конференция AI&BigData Lab
Александр Конопко "Celos: оркестрирование и тестирование задач Hadoop"
В компании Collective используется более сотни Hadoop задач. Проблема их мониторинга и оркестрирования стояла очень остро. Для решения этой проблемы была разработана система Celos, которая существенно упростила работу технических инжинеров в компании. В этом докладе я познакомлю слушателя с и предложу наш способ решения этих проблем.
Подробнее:
http://geekslab.co/
https://www.facebook.com/GeeksLab.co
https://www.youtube.com/user/GeeksLabVideo
No Callbacks, No Threads - RailsConf 2010Ilya Grigorik
Multi-threaded servers compete for the global interpreter lock (GIL) and incur the cost of continuous context switching, potential deadlocks, or plain wasted cycles. Asynchronous servers, on the other hand, create a mess of callbacks and errbacks, complicating the code. But, what if, you could get all the benefits of asynchronous programming, while preserving the synchronous look and feel of the code – no threads, no callbacks?
Domains were added to Node.js in 0.8, but their use and workings have been a relative mystery. In short, domains are a structured way of reacting to uncaught exceptions; for example, when creating an HTTP server, you can use domains to send 500 errors when exceptions occur instead of crashing your server. This talk will go over what domains are, how to use them, and some of the subtleties behind how they work.
Droidcon Berlin 2021 - With coroutines being the de facto way of exposing async work and streams of changes for Kotlin on Android, developers are obviously attempting to use the same approaches when moving their code to Multiplatform.
But due to the way the memory model differs between JVM and Kotlin Native, it can be a painful experience.
In this talk, we will take a deep dive into the Coroutine API for Kotlin Multiplatform. You will learn how to expose your API with Coroutines while working with the Kotlin Native memory model instead of against it, and avoid the dragons along the way.
An attempt to see how node is faster than (PHP+Acpache) stack where situations are similar and none of them are tweaked from their default configuration
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...GeeksLab Odessa
23.05.15 Одесса. Impact Hub Odessa. Конференция AI&BigData Lab
Александр Конопко "Celos: оркестрирование и тестирование задач Hadoop"
В компании Collective используется более сотни Hadoop задач. Проблема их мониторинга и оркестрирования стояла очень остро. Для решения этой проблемы была разработана система Celos, которая существенно упростила работу технических инжинеров в компании. В этом докладе я познакомлю слушателя с и предложу наш способ решения этих проблем.
Подробнее:
http://geekslab.co/
https://www.facebook.com/GeeksLab.co
https://www.youtube.com/user/GeeksLabVideo
me ranting about the downsides of Spring Boot / Netflix OSS. Sorry that the slides are a little rare on text, so most likely hard to understand without the actual talk. feel free to send me any questions, though!
It shows the implementation of an Indy Server which communicates with a client over TCP and Sockets. I made it script able to demonstrate the fascination of 2 boxes communicate with each other at the same time.
DEF CON 23: Stick That In Your (root)Pipe & Smoke ItSynack
DEF CON 23
You may ask; "why would Apple add an XPC service that can create setuid files anywhere on the system - and then blindly allow any local user to leverage this service?" Honestly, I have no idea!
The undocumented 'writeconfig' XPC service was recently uncovered by Emil Kvarnhammar, who determined its lax controls could be abused to escalate one's privileges to root. Dubbed ‘rootpipe,' this bug was patched in OS X 10.10.3. End of story, right? Nope, instead things then got quite interesting. First, Apple decided to leave older versions of OS X un-patched. Then, an astute researcher discovered that the OSX/XSLCmd malware which pre-dated the disclosure, exploited this same vulnerability as a 0day! Finally, yours truly, found a simple way to side-step Apple's patch to re-exploit the core vulnerability on a fully-patched system. So come attend (but maybe leave your MacBooks at home), as we dive into the technical details XPC and the rootpipe vulnerability, explore how malware exploited this flaw, and then fully detail the process of completely bypassing Apple's patch. The talk will conclude by examining Apple’s response, a second patch, that appears to squash ‘rootpipe’…for now.
A brief look at a few IP cameras, wireless extenders and routers - a significant number have unpatched issues such as cross-site scripting, cross-site request forgery and authentication bypass, meaning we can take control of devices, change wireless settings and obtain a copy of all video on certain devices, all by having the unsuspecting user visit a web page we control.
Containers, Docker, and Microservices: the Terrific TrioJérôme Petazzoni
One of the upsides of Microservices is the ability to deploy often,at arbitrary schedules, and independently of other services, instead of requiring synchronized deployments happening on a fixed time.
But to really leverage this advantage, we need fast, efficient, and reliable deployment processes. That's one of the value propositions of Containers in general, and Docker in particular.
Docker offers a new, lightweight approach to application portability.It can build applications using easy-to-write, repeatable, efficient recipes; then it can ship them across environments using a common container format; and it can run them within isolated namespaces which abstract the operating environment, independently of the distribution,versions, network setup, and other details of this environment.
But Docker can do way more than deploy your apps. Docker also enables you to generalize Microservices principles and apply them on operational tasks like logging, remote access, backups, and troubleshooting.This decoupling results in independent, smaller, simpler moving parts.
Async task, threads, pools, and executors oh my!Stacy Devino
http://360andev.com/sessions/100-async-task-threads-pools-and-executors/
Frome 360 AnDev conference
There are many ways to use Threads and in the multithreaded world in which we live, it can be confusing when, where, and how to use these functions correctly. Still, that assumes you know what they all mean and how to manipulate them. Novices and Experts welcome as there are many schools of thought, but we will explore them all together.
Don’t worry, we have you covered.
Animated Version : but.ly/asyncThread
Similar to Implementation of a state machine for a longrunning background task in android service (20)
How can you arrange the words of an input text lexicographically? We can do it using Brute Force method.But is there any other better way? Yes, there are. One such way is by using Trie or Prefix Tree Data Structure. This document shows how to do it using practical code.
The Designing of a Software System from scratch with the help of OOAD & UML -...Somenath Mukhopadhyay
This document explains how to design a piece of software from the scratch through UML and OOAD principles. I have taken a Restaurant system for the example.
Structural Relationship between Content Resolver and Content Provider of Andr...Somenath Mukhopadhyay
This document describes the structural relationship between Content Resolver and Content Provider and explains how it resembles the Proxy Design Pattern described by the GoF.
This document describes the internals of how Asynctask of Android works internally and its similarities with half-sync half-async design pattern as described in Pattern Oriented Software Architecture or POSA2.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Implementation of a state machine for a longrunning background task in android service
1. Implementation of a State machine for a long
running background task in an Android service
by
Somenath Mukhopadhyay
som.mukhopadhyay@gmail.com
In the below example i will show how we can break a long running background task running in a
service into different states of a state machine and notify the front end UI about each and every
stage as they occur in the service. Here i have used a service called LongRunningService which
actually (theoretically) does the task of downloading a big file from a network server (however, for
simplicity i have just stubbed out the actual download code with a thread having delay of 1000
ms). This background task has been splitted into different states according to the state machine
like “Start Connection”, “Connection Completed”, “Start Downloading” and “Stop Downloading”.
This application also showcases the concept of communicating from a background service to
the frontend UI through Android messenger framework.
So lets start digging into the source code of the application.
First of all the main Activity class.
As it is clear from the code that the main activity has a messenger whose message handling
part has been defined by a class called MessageHandler (derived from Handler). This is the
messenger object through which the background service notifies the UI thread.
The UI has a button. Upon clicking it, it starts the service and as soon as it starts the service the
service starts notifying about the different states of the Service through the messenger.
This is pretty simple. Right!!!
The class MainActivity.Java
package com.somitsolutions.android.example.statepatterninservice;
import
import
import
import
android.app.Activity;
android.content.Context;
android.content.Intent;
android.os.Bundle;
2. import
import
import
import
import
import
import
import
android.os.Handler;
android.os.Message;
android.os.Messenger;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private static final int CONNECTING = 1;
private static final int CONNECTED = 2;
private static final int DOWNLOADSTARTED = 3;
private static final int DOWNLOADFINISHED = 4;
Button startButton;
private MessageHandler handler;
private static MainActivity mMainActivity;
public Messenger mMessenger = new Messenger(new MessageHandler(this));
private class MessageHandler extends Handler{
private Context c;
MessageHandler(Context c){
this.c = c;
}
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case CONNECTING:
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
break;
case CONNECTED:
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
break;
case DOWNLOADSTARTED:
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
break;
case DOWNLOADFINISHED:
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
break;
default:
super.handleMessage(msg);
"Connecting",
"Connected",
"Download Started",
"Download Finished",
3. }
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainActivity = this;
startButton = (Button)findViewById(R.id.button1);
startButton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static MainActivity getMainActivity(){
return mMainActivity;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent serv = new Intent(MainActivity.this, LongRunningService.class);
startService(serv);
}
}
Now lets start digging the LongrunningServivce class.
As we know that a service usually runs in the main thread. Hence the UI thread may seem to be
frozen in case of a long background service. To overcome that a background thread is being
created the moment one starts the service and the task is executed in that thread. This is clear
from the following piece of code.
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
4. // separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Thread.NORM_PRIORITY);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
The service class also has a Handler class called ServiceHandler through which we send
messages from the service to the thread’s message loop. Inside the message loop, we actually
accomplish the long running task. Lets have a look at this ServiceHandler class
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
Messenger messenger= MainActivity.getMainActivity().mMessenger;
try {
messenger.send(Message.obtain(null, CONNECTING, "Connecting"));
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 10 seconds.
Thread.sleep(1000);
// Normally we would do some work here, like download a
file.
// For our sample, we just sleep for 10 seconds.
messenger.send(Message.obtain(null, CONNECTED,
"Connected"));
// Normally we would do some work here, like download a
file.
// For our sample, we just sleep for 10 seconds.
Thread.sleep(1000);
messenger.send(Message.obtain(null,
5. DOWNLOADSTARTED, "Download Started"));
// Normally we would do some work here, like download a
file.
// For our sample, we just sleep for 10 seconds.
Thread.sleep(1000);
messenger.send(Message.obtain(null,
DOWNLOADFINISHED, "Download Finished"));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
As it becomes clear from the above code that in this overridden HandleMessage function of the
service handler, we acquire a reference to the messenger of the main activity and it falls through
different states like “Connecting”, “Connected”, “Start Downloading” and “Finish Downloading”. In
each state a different integer constant is being passed to the UI thread through the messenger.
In the main UI thread the handler function of the messenger handles these messages from the
service and displays the status of the each state.
After that the service stops itself.
package com.somitsolutions.android.example.statepatterninservice;
import
import
import
import
import
import
import
import
import
android.app.Service;
android.content.Intent;
android.os.Handler;
android.os.HandlerThread;
android.os.IBinder;
android.os.Looper;
android.os.Message;
android.os.Messenger;
android.os.RemoteException;
6. import android.widget.Toast;
public class LongRunningService extends Service {
private
private
private
private
static
static
static
static
final
final
final
final
int
int
int
int
CONNECTING = 1;
CONNECTED = 2;
DOWNLOADSTARTED = 3;
DOWNLOADFINISHED = 4;
private Looper mServiceLooper;
private ServiceHandler mServiceHandler; // Handler that receives messages from
the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
Messenger messenger= MainActivity.getMainActivity().mMessenger;
try {
messenger.send(Message.obtain(null, CONNECTING, "Connecting"));
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 10 seconds.
Thread.sleep(1000);
// Normally we would do some work here, like download a
file.
// For our sample, we just sleep for 10 seconds.
messenger.send(Message.obtain(null, CONNECTED,
"Connected"));
// Normally we would do some work here, like download a
file.
// For our sample, we just sleep for 10 seconds.
Thread.sleep(1000);
messenger.send(Message.obtain(null,
DOWNLOADSTARTED, "Download Started"));
// Normally we would do some work here, like download a
file.
// For our sample, we just sleep for 10 seconds.
Thread.sleep(1000);
7. messenger.send(Message.obtain(null,
DOWNLOADFINISHED, "Download Finished"));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Thread.NORM_PRIORITY);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "download service starting",
Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
8. @Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
The main.xml layout file looks like the following:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="165dp"
android:text="Start Service" />
</RelativeLayout>
And the manifest file of this application is as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.somitsolutions.android.example.statepatterninservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />