SlideShare une entreprise Scribd logo
1  sur  16
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

Contenu connexe

Tendances

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
 
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 AirflowRomain Dorgueil
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš 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 extensionsOleksandr 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 OperationsNeo4j
 
"Ускорение сборки большого проекта на 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 androidEsa 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 modelingCodemotion
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy 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 RxJavaFrank Lyaruu
 
RubyKaigi2015 making robots-with-mruby
RubyKaigi2015 making robots-with-mrubyRubyKaigi2015 making robots-with-mruby
RubyKaigi2015 making robots-with-mrubyyamanekko
 
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 sourceDavid Brimley
 

Tendances (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
 

Similaire à Theads services

ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6Andy 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.pdfShaiAlmog1
 
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 Responsesdarrelmiller71
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applicationslmrei
 
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 JetpackNelson 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 InfrastructureNicolas 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 VIHari Christian
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
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 developersJSFestUA
 
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 & JetpackNelson 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 Shinyanamarisaguedes
 

Similaire à 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
 

Plus de 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
 

Dernier

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Dernier (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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)