SlideShare a Scribd company logo
l

Threads and Services
l

Background Processes
l

l

l

Threads

Recall that Android ensures responsive apps by enforcing a
5 second limit on Activities
Sometimes we need to do things that take longer than 5
seconds, or that can be done while the user does something
else
l

l

l

Threads

Activities, Services, and Broadcast Receivers run on the
main application thread
We can start background/child threads to do things for us
•
•
•
•
•
•
•

private void methodInAndroidClass() {
Threads
Thread thread = new Thread(null, doSomething, “Background”);
Thread.start();
}
private Runnable doSomething = new Runnable() {
public void run() { /* do the something here */ }
};
l

• private void methodInAndroidClass() {
• new Thread(){
•
public void run() {/* do the something here */ }
• }.start();
•}
• @Override
•
public void onCreate(Bundle savedInstanceState) {
•
super.onCreate(savedInstanceState);
•
setContentView(R.layout.main);
•
new Thread() {
•
public void run() {
• Get data from web in background
•
String maps = null;
•
try {
•
URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt");
•
URLConnection conn = updateURL.openConnection();
•
int contentLength = conn.getContentLength();
•
InputStream is = conn.getInputStream();
•
BufferedInputStream bis = new BufferedInputStream(is,1024);
•
ByteArrayBuffer baf = new ByteArrayBuffer(contentLength);
•
int current = 0;
•
while((current = bis.read()) != -1){
•
baf.append((byte)current);
}
•
maps = new String(baf.toByteArray()); //Convert the Bytes read to a String.
•
} catch (Exception e) {}
•
}
• Now we want to display data on screen
•
}.start();
• }
• public void onCreate(Bundle savedInstanceState) {
•
super.onCreate(savedInstanceState);
•
setContentView(R.layout.main);
•
TextView hello = (TextView)this.findViewById(R.id.hellotv);
•
hello.setText("testing");
•
new Thread() {
•
public void run() {
•
String maps = null;
•
try {
•
URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt");
•
URLConnection conn = updateURL.openConnection();
•
int contentLength = conn.getContentLength();
•
InputStream is = conn.getInputStream();
•
BufferedInputStream bis = new BufferedInputStream(is,1024);
•
ByteArrayBuffer baf = new ByteArrayBuffer(contentLength);
•
int current = 0;
•
while((current = bis.read()) != -1){
•
baf.append((byte)current);
•
}
•
maps = new String(baf.toByteArray()); //Convert the Bytes read to a String.
•
} catch (Exception e) {}
•
TextView hello = (TextView)findViewById(R.id.hellotv);
•
• CalledFromWrongThreadException: Only the original
hello.setText(maps);
•
}}.start(); • thread that created a view hierarchy can touch its views.
l
l

l

Android Thread Constraints

Child threads cannot access UI elements (views); these must
be accessed through the main thread
What to do?
l Give results to main thread and let it use results
l In Campus Maps I set a flag in the thread, then I added the
menu item dynamically in Activity.onPrepareOptionsMenu
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView hello = (TextView)this.findViewById(R.id.hellotv);
hello.setText("testing");
new Thread() {
public void run() {
String maps = null;
try {
URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt");
URLConnection conn = updateURL.openConnection();
int contentLength = conn.getContentLength();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,1024);
ByteArrayBuffer baf = new ByteArrayBuffer(contentLength);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
maps = new String(baf.toByteArray()); //Convert the Bytes read to a String.
} catch (Exception e) {}
hello.setText(maps);
}}.start();
l

l

Post to GUI Thread

Handler allows you to post Messages and Runnable objects
to threads
l These can be scheduled to run at some point in the future,
or enqueued for another thread
l We will use the latter
• public class BackgroundDemos extends Activity {
•
private Handler handler = new Handler();
•
private String maps = null;
•
TextView hello;
•
@Override
•
public void onCreate(Bundle savedInstanceState) {
•
super.onCreate(savedInstanceState);
•
setContentView(R.layout.main);
•
hello = (TextView)this.findViewById(R.id.hellotv);
•
hello.setText("testing");
•
new Thread() {
•
public void run() {
•
try {
•
URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt");
•
//code omitted here
•
maps = new String(baf.toByteArray()); //Convert the Bytes read to a String.
•
handler.post(doUpdateMaps);
•
} catch (Exception e) {} } }.start();
•
}
•
private Runnable doUpdateMaps = new Runnable() {
•
public void run() {
•
hello.setText(maps);
•
}
•
};}
l

l
l

Services are like Activities, but without a UI
Services are not intended as background threads
l

l
l

Services

Think of a media player where the song keeps playing
while the user looks for more songs to play or uses other
apps
Don’t think of a cron job (e.g. run every day at 3am), use
Alarms to do this

Several changes in 2.0 related to Services
l

See http://androiddevelopers.blogspot.com/2010/02/service-api-changesstarting-with.html
l

Add to AndroidManifest.xml

l

Create the Service class

• <service android:enabled=“true” android:name=“.NewMapService”></service>
• public class NewMapService extends Service {
•
@Override
•
public void onCreate() {
•
}
•
@Override
•
public void onStart(Intent intent, int startId) {
•
//do something
•
}
•
@Override
•
public IBinder onBind(Intent intent) {
•
return null;
•
}
• }
l

l

Start/Stop the Service

Other alternatives in text

• public class MyActivity extends Activity {
•
@Override
•
public void onCreate() {
•
…
•
startService(new Intent(this, NewMapService.class);
•
}
•
@Override
•
public void onStop() {
•
…
•
stopService(new Intent(this, NewMapService.class));
• }
• }
l

•
•
•
•
•
•
•
•
•
•
•
•

Status Bar Notifications

NotificationManager nm = (NotificationManager)getSystemService(
Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,
"NewMaps",System.currentTimeMillis());
String expandedTitle = "New Map Service";
String expandedText = "New Map Service is running";
Intent i = new Intent(this, NewMapService.class);
PendingIntent launchIntent = PendingIntent.getActivity(
getApplicationContext(), 0, i, 0);
notification.setLatestEventInfo(getApplicationContext(), expandedTitle,
expandedText, launchIntent);
nm.notify(1,notification);

• nm.cancel(1); //cancel a notification (id/parameters must match)
l

l
l
l
l

Other Notification

Sounds
Vibration
Flashing lights
Ongoing and Insistent

More Related Content

What's hot

Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams
Seiya Mizuno
 
Moar tools for asynchrony!
Moar tools for asynchrony!Moar tools for asynchrony!
Moar tools for asynchrony!
Joachim Bengtsson
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
Bo-Young Park
 
Draw More, Work Less
Draw More, Work LessDraw More, Work Less
Draw More, Work Less
Michael Bar-Sinai
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
Bo-Young Park
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Romain Dorgueil
 
Ruby meets Go
Ruby meets GoRuby meets Go
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensions
Oleksandr Zhevzhyk
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
Neo4j
 
"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)
"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)
"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)
AvitoTech
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
Esa Firman
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
Troy Miles
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu
 
RubyKaigi2015 making robots-with-mruby
RubyKaigi2015 making robots-with-mrubyRubyKaigi2015 making robots-with-mruby
RubyKaigi2015 making robots-with-mruby
yamanekko
 
Devoxx uk 2014 High performance in-memory Java with open source
Devoxx uk 2014   High performance in-memory Java with open sourceDevoxx uk 2014   High performance in-memory Java with open source
Devoxx uk 2014 High performance in-memory Java with open source
David Brimley
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
Derek Willian Stavis
 

What's hot (20)

Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams
 
Moar tools for asynchrony!
Moar tools for asynchrony!Moar tools for asynchrony!
Moar tools for asynchrony!
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
Draw More, Work Less
Draw More, Work LessDraw More, Work Less
Draw More, Work Less
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
Ruby meets Go
Ruby meets GoRuby meets Go
Ruby meets Go
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensions
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)
"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)
"Ускорение сборки большого проекта на Objective-C + Swift" Иван Бондарь (Avito)
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
RubyKaigi2015 making robots-with-mruby
RubyKaigi2015 making robots-with-mrubyRubyKaigi2015 making robots-with-mruby
RubyKaigi2015 making robots-with-mruby
 
Devoxx uk 2014 High performance in-memory Java with open source
Devoxx uk 2014   High performance in-memory Java with open sourceDevoxx uk 2014   High performance in-memory Java with open source
Devoxx uk 2014 High performance in-memory Java with open source
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
 

Similar to Theads services

ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
Andy Butland
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Sam Muhanguzi
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
Dina Goldshtein
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdf
ShaiAlmog1
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
Norberto Leite
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
MongoDB
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
darrelmiller71
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
lmrei
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
Nelson Glauber Leal
 
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
Fons Sonnemans
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
Nicolas Corrarello
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
Hari Christian
 
Kotlin talk
Kotlin talkKotlin talk
Kotlin talk
Klemen Kresnik
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
Petr Dvorak
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
Felix Geisendörfer
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JSFestUA
 
Group111
Group111Group111
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 
Introduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R ShinyIntroduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R Shiny
anamarisaguedes
 

Similar to Theads services (20)

ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdf
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
 
JS Essence
JS EssenceJS Essence
JS Essence
 
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 
Kotlin talk
Kotlin talkKotlin talk
Kotlin talk
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
 
Group111
Group111Group111
Group111
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Introduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R ShinyIntroduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R Shiny
 

More from Training Guide

Map
MapMap
Persistences
PersistencesPersistences
Persistences
Training Guide
 
Application lifecycle
Application lifecycleApplication lifecycle
Application lifecycle
Training Guide
 
Intents broadcastreceivers
Intents broadcastreceiversIntents broadcastreceivers
Intents broadcastreceiversTraining Guide
 

More from Training Guide (8)

Map
MapMap
Map
 
Persistences
PersistencesPersistences
Persistences
 
App basic
App basicApp basic
App basic
 
Application lifecycle
Application lifecycleApplication lifecycle
Application lifecycle
 
Deployment
DeploymentDeployment
Deployment
 
Getting started
Getting startedGetting started
Getting started
 
Intents broadcastreceivers
Intents broadcastreceiversIntents broadcastreceivers
Intents broadcastreceivers
 
Tdd
TddTdd
Tdd
 

Recently uploaded

From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 

Recently uploaded (20)

From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 

Theads services

  • 3. l l l Threads Recall that Android ensures responsive apps by enforcing a 5 second limit on Activities Sometimes we need to do things that take longer than 5 seconds, or that can be done while the user does something else
  • 4. l l l Threads Activities, Services, and Broadcast Receivers run on the main application thread We can start background/child threads to do things for us
  • 5. • • • • • • • private void methodInAndroidClass() { Threads Thread thread = new Thread(null, doSomething, “Background”); Thread.start(); } private Runnable doSomething = new Runnable() { public void run() { /* do the something here */ } }; l • private void methodInAndroidClass() { • new Thread(){ • public void run() {/* do the something here */ } • }.start(); •}
  • 6. • @Override • public void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); • setContentView(R.layout.main); • new Thread() { • public void run() { • Get data from web in background • String maps = null; • try { • URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt"); • URLConnection conn = updateURL.openConnection(); • int contentLength = conn.getContentLength(); • InputStream is = conn.getInputStream(); • BufferedInputStream bis = new BufferedInputStream(is,1024); • ByteArrayBuffer baf = new ByteArrayBuffer(contentLength); • int current = 0; • while((current = bis.read()) != -1){ • baf.append((byte)current); } • maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. • } catch (Exception e) {} • } • Now we want to display data on screen • }.start(); • }
  • 7. • public void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); • setContentView(R.layout.main); • TextView hello = (TextView)this.findViewById(R.id.hellotv); • hello.setText("testing"); • new Thread() { • public void run() { • String maps = null; • try { • URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt"); • URLConnection conn = updateURL.openConnection(); • int contentLength = conn.getContentLength(); • InputStream is = conn.getInputStream(); • BufferedInputStream bis = new BufferedInputStream(is,1024); • ByteArrayBuffer baf = new ByteArrayBuffer(contentLength); • int current = 0; • while((current = bis.read()) != -1){ • baf.append((byte)current); • } • maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. • } catch (Exception e) {} • TextView hello = (TextView)findViewById(R.id.hellotv); • • CalledFromWrongThreadException: Only the original hello.setText(maps); • }}.start(); • thread that created a view hierarchy can touch its views.
  • 8. l l l Android Thread Constraints Child threads cannot access UI elements (views); these must be accessed through the main thread What to do? l Give results to main thread and let it use results l In Campus Maps I set a flag in the thread, then I added the menu item dynamically in Activity.onPrepareOptionsMenu
  • 9. • • • • • • • • • • • • • • • • • • • • • • • • public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView hello = (TextView)this.findViewById(R.id.hellotv); hello.setText("testing"); new Thread() { public void run() { String maps = null; try { URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt"); URLConnection conn = updateURL.openConnection(); int contentLength = conn.getContentLength(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is,1024); ByteArrayBuffer baf = new ByteArrayBuffer(contentLength); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. } catch (Exception e) {} hello.setText(maps); }}.start();
  • 10. l l Post to GUI Thread Handler allows you to post Messages and Runnable objects to threads l These can be scheduled to run at some point in the future, or enqueued for another thread l We will use the latter
  • 11. • public class BackgroundDemos extends Activity { • private Handler handler = new Handler(); • private String maps = null; • TextView hello; • @Override • public void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); • setContentView(R.layout.main); • hello = (TextView)this.findViewById(R.id.hellotv); • hello.setText("testing"); • new Thread() { • public void run() { • try { • URL updateURL = new URL("http://simexusa.com/cm/mapdata.txt"); • //code omitted here • maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. • handler.post(doUpdateMaps); • } catch (Exception e) {} } }.start(); • } • private Runnable doUpdateMaps = new Runnable() { • public void run() { • hello.setText(maps); • } • };}
  • 12. l l l Services are like Activities, but without a UI Services are not intended as background threads l l l Services Think of a media player where the song keeps playing while the user looks for more songs to play or uses other apps Don’t think of a cron job (e.g. run every day at 3am), use Alarms to do this Several changes in 2.0 related to Services l See http://androiddevelopers.blogspot.com/2010/02/service-api-changesstarting-with.html
  • 13. l Add to AndroidManifest.xml l Create the Service class • <service android:enabled=“true” android:name=“.NewMapService”></service> • public class NewMapService extends Service { • @Override • public void onCreate() { • } • @Override • public void onStart(Intent intent, int startId) { • //do something • } • @Override • public IBinder onBind(Intent intent) { • return null; • } • }
  • 14. l l Start/Stop the Service Other alternatives in text • public class MyActivity extends Activity { • @Override • public void onCreate() { • … • startService(new Intent(this, NewMapService.class); • } • @Override • public void onStop() { • … • stopService(new Intent(this, NewMapService.class)); • } • }
  • 15. l • • • • • • • • • • • • Status Bar Notifications NotificationManager nm = (NotificationManager)getSystemService( Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon, "NewMaps",System.currentTimeMillis()); String expandedTitle = "New Map Service"; String expandedText = "New Map Service is running"; Intent i = new Intent(this, NewMapService.class); PendingIntent launchIntent = PendingIntent.getActivity( getApplicationContext(), 0, i, 0); notification.setLatestEventInfo(getApplicationContext(), expandedTitle, expandedText, launchIntent); nm.notify(1,notification); • nm.cancel(1); //cancel a notification (id/parameters must match)