SlideShare a Scribd company logo
1 of 15
6/18/2013 1
Android Threading – Handlers and Async Tasks
Android Widgets
6/18/2013 2
Processes and Threads in Android
Processes
By default, all components of the same application run in the same process and most applications should not
change this.
The manifest entry for each type of component element—<activity>, <service>, <receiver>, and <provider>—
supports an android:process attribute that can specify a process in which that component should run.
Threads
When an application is launched, the system creates a thread of execution for the application, called "main."
This thread is very important because it is in charge of dispatching events to the appropriate user interface
widgets, including drawing events.
The system does not create a separate thread for each instance of a component. All components that run in
the same process are instantiated in the UI thread, and system calls to each component are dispatched from
that thread.
6/18/2013 3
Process lifecycle
The Android system tries to maintain an application process for as long as possible, but eventually needs to
remove old processes to reclaim memory for new or more important processes. To determine which
processes to keep and which to kill, the system places each process into an "importance hierarchy" based on
the components running in the process and the state of those components.
There are five levels in the importance hierarchy. The following list presents the different types of processes
in order of importance (the first process is most important and is killed last):
1. Foreground process : A process that is required for what the user is currently doing. A process is
considered to be in the foreground if any of the following conditions are true:
• It hosts an Activity that the user is interacting with (the Activity's onResume() method has been
called).
• It hosts a Service that's bound to the activity that the user is interacting with.
• It hosts a Service that's running "in the foreground"—the service has called startForeground().
• It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
• It hosts a BroadcastReceiver that's executing its onReceive() method.
Generally, only a few foreground processes exist at any given time. They are killed only as a last resort—
if memory is so low that they cannot all continue to run.
6/18/2013 4
2. Visible process : A process that doesn't have any foreground components, but still can affect what the user
sees on screen. A process is considered to be visible if either of the following conditions are true:
• It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has
been called). This might occur, for example, if the foreground activity started a dialog, which allows the
previous activity to be seen behind it.
• It hosts a Service that's bound to a visible (or foreground) activity.
A visible process is considered extremely important and will not be killed unless doing so is required to keep all
foreground processes running.
3. Service process : A process that is running a service that has been started with the startService() method and
does not fall into either of the two higher categories.
4. Background process : A process holding an activity that's not currently visible to the user (the activity's
onStop() method has been called). These processes have no direct impact on the user experience, and the
system can kill them at any time to reclaim memory for a foreground, visible, or service process.
5. Empty process : A process that doesn't hold any active application components. The only reason to keep this
kind of process alive is for caching purposes, to improve startup time the next time a component needs to run
in it.
6/18/2013 5
Thread Management Principles
When your app performs intensive work in response to user interaction, this single thread model can yield
poor performance unless you implement your application properly. Specifically, if everything is happening in
the UI thread, performing long operations such as network access or database queries will block the whole UI.
Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker
thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two
rules to Android's single thread model:
1. Do not block the UI thread
2. Do not access the Android UI toolkit from outside the UI thread
6/18/2013 6
Thread Management using Handlers
Because of the single thread model described above, it's vital to the responsiveness of your application's UI
that you do not block the UI thread. If you have operations to perform that are not instantaneous, you should
make sure to do them in separate threads ("background" or "worker" threads).
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
} }).start();
}
At first, this seems to work fine, because it creates a new thread to handle the network
operation. However, it violates the second rule of the single-threaded model: do not access
the Android UI toolkit from outside the UI thread—this sample modifies the ImageView
from the worker thread instead of the UI thread.
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap bitmap =
loadImageFromNetwork("http://example.com/image.png");
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
}).start();
}
6/18/2013 7
Thread Management using AsyncTasks
AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking
operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle
threads and/or handlers yourself.
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
To use it, you must subclass AsyncTask and implement the doInBackground() callback method, which runs in a
pool of background threads. To update your UI, you should implement onPostExecute(), which delivers the result
from doInBackground() and runs in the UI thread, so you can safely update your UI. You can then run the task by
calling execute() from the UI thread.
6/18/2013 8
Android Widgets
6/18/2013 9
What is a Widget ?
App Widgets are miniature application views that can be embedded in other applications (such as the Home
screen) and receive periodic updates.
The Basics of a widget :
To create an App Widget, you need the following:
AppWidgetProviderInfo object : Describes the metadata for an App Widget, such as the App Widget's layout,
update frequency, and the AppWidgetProvider class. This should be defined in XML.
AppWidgetProvider class implementation : Defines the basic methods that allow you to programmatically
interface with the App Widget, based on broadcast events. Through it, you will receive broadcasts when the
App Widget is updated, enabled, disabled and deleted.
View layout : Defines the initial layout for the App Widget, defined in XML.
6/18/2013 10
Steps to Create a Widget
Step 1 : Declaring the manifest
<receiver android:name="ExampleAppWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/example_appwidget_info" />
</receiver>
The <receiver> element requires the android:name attribute, which specifies the AppWidgetProvider used by the App
Widget.
The <intent-filter> element must include an <action> element with the android:name attribute. This attribute specifies
that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast that you must
explicitly declare. The AppWidgetManager automatically sends all other App Widget broadcasts to the AppWidgetProvider
as necessary.
The <meta-data> element specifies the AppWidgetProviderInfo resource and requires the following attributes:
1. android:name - Specifies the metadata name. Use android.appwidget.provider to identify the data as the
AppWidgetProviderInfo descriptor.
2. android:resource - Specifies the AppWidgetProviderInfo resource location.
6/18/2013 11
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="40dp"
android:minHeight="40dp"
android:updatePeriodMillis="86400000"
android:previewImage="@drawable/preview"
android:initialLayout="@layout/example_appwidget"
android:configure="com.example.android.ExampleAppWidgetConfigure"
android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen|keyguard"
android:initialKeyguardLayout="@layout/example_keyguard">
</appwidget-provider>
Step 2 : Writing the appwidget-provider metadata.
Step 3 : Creating App widget layout
You must define an initial layout for your App Widget in XML and save it in the project's res/layout/ directory.
You can design your App Widget using the View objects
6/18/2013 12
Step 4 : Writing the AppWidgetProvider class
The AppWidgetProvider class extends BroadcastReceiver as a convenience class to handle the App Widget
broadcasts. The AppWidgetProvider receives only the event broadcasts that are relevant to the App Widget, such as
when the App Widget is updated, deleted, enabled, and disabled.
onUpdate() : This is called to update the App Widget at intervals defined by the updatePeriodMillis attribute
in the AppWidgetProviderInfo (see Adding the AppWidgetProviderInfo Metadata above). This method is also
called when the user adds the App Widget, so it should perform the essential setup, such as define event
handlers for Views and start a temporary Service, if necessary. However, if you have declared a configuration
Activity, this method is not called when the user adds the App Widget, but is called for the subsequent
updates.
onAppWidgetOptionsChanged() : This is called when the widget is first placed and any time the widget
is resized. You can use this callback to show or hide content based on the widget's size ranges.
6/18/2013 13
onDeleted(Context, int[]) : This is called every time an App Widget is deleted from the App Widget host.
onEnabled(Context) : This is called when an instance the App Widget is created for the first time. For example,
if the user adds two instances of your App Widget, this is only called the first time. If you need to open a new
database or perform other setup that only needs to occur once for all App Widget instances, then this is a good
place to do it.
onDisabled(Context) : This is called when the last instance of your App Widget is deleted from the App Widget
host. This is where you should clean up any work done in onEnabled(Context), such as delete a temporary
database.
onReceive(Context, Intent) : This is called for every broadcast and before each of the above callback methods.
You normally don't need to implement this method because the default AppWidgetProvider implementation
filters all App Widget broadcasts and calls the above methods as appropriate.
6/18/2013 14
Step 5 : Creating an App Widget Configuration Activity
Defining the activity in the mainfest
<activity android:name=".ExampleAppWidgetConfigure">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
1. First, get the App Widget ID from the Intent that launched the Activity:
2. Perform your App Widget configuration.
3. When the configuration is complete, get an instance of the AppWidgetManager by calling
getInstance(Context):
4. Finally, create the return Intent, set it with the Activity result, and finish the Activity:
6/18/2013 15
Step 6 : Enabling App Widgets on the Lockscreen and Setting the Preview image
Android 4.2 introduces the ability for users to add widgets to the lock screen. To indicate that your app widget is
available for use on the lock screen, declare the android:widgetCategory attribute in the XML file that specifies
your AppWidgetProviderInfo.
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
...
android:widgetCategory="keyguard|home_screen">
</appwidget-provider>

More Related Content

Viewers also liked

Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recieversUtkarsh Mankad
 
Android Internal Services
Android Internal ServicesAndroid Internal Services
Android Internal ServicesNanik Tolaram
 
Diving inside Android Wifi
Diving inside Android WifiDiving inside Android Wifi
Diving inside Android WifiNanik Tolaram
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
 
Android Security Essentials
Android Security EssentialsAndroid Security Essentials
Android Security EssentialsOSCON Byrum
 
Ch5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetCh5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetShih-Hsiang Lin
 
Adapter and cache technique
Adapter and cache techniqueAdapter and cache technique
Adapter and cache techniqueHoang Vy Nguyen
 
Intents broadcastreceivers
Intents broadcastreceiversIntents broadcastreceivers
Intents broadcastreceiversTraining Guide
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Johan Nilsson
 
Android Services Skill Sprint
Android Services Skill SprintAndroid Services Skill Sprint
Android Services Skill SprintJim McKeeth
 
Android Interview Questions
Android Interview QuestionsAndroid Interview Questions
Android Interview QuestionsGaurav Mehta
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in AndroidPerfect APK
 
Clean Architecture by Andrzej Bednarz
Clean Architecture by Andrzej BednarzClean Architecture by Andrzej Bednarz
Clean Architecture by Andrzej BednarzNetworkedAssets
 
Android interview questions for 2 to 5 years (1)
Android interview questions for 2 to 5 years (1)Android interview questions for 2 to 5 years (1)
Android interview questions for 2 to 5 years (1)satish reddy
 
[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers[Android] Services and Broadcast Receivers
[Android] Services and Broadcast ReceiversNikmesoft Ltd
 
Connecting to Web Services on Android June 2 2010
Connecting to Web Services on Android June 2 2010Connecting to Web Services on Android June 2 2010
Connecting to Web Services on Android June 2 2010sullis
 

Viewers also liked (20)

Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Android Internal Services
Android Internal ServicesAndroid Internal Services
Android Internal Services
 
Android Source Code
Android Source CodeAndroid Source Code
Android Source Code
 
Diving inside Android Wifi
Diving inside Android WifiDiving inside Android Wifi
Diving inside Android Wifi
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Custom components
Custom componentsCustom components
Custom components
 
Session 3 beccse
Session 3 beccseSession 3 beccse
Session 3 beccse
 
Android Security Essentials
Android Security EssentialsAndroid Security Essentials
Android Security Essentials
 
Ch5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetCh5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internet
 
Adapter and cache technique
Adapter and cache techniqueAdapter and cache technique
Adapter and cache technique
 
Intents broadcastreceivers
Intents broadcastreceiversIntents broadcastreceivers
Intents broadcastreceivers
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011
 
Android Services Skill Sprint
Android Services Skill SprintAndroid Services Skill Sprint
Android Services Skill Sprint
 
Android Interview Questions
Android Interview QuestionsAndroid Interview Questions
Android Interview Questions
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in Android
 
Clean Architecture by Andrzej Bednarz
Clean Architecture by Andrzej BednarzClean Architecture by Andrzej Bednarz
Clean Architecture by Andrzej Bednarz
 
Android interview questions for 2 to 5 years (1)
Android interview questions for 2 to 5 years (1)Android interview questions for 2 to 5 years (1)
Android interview questions for 2 to 5 years (1)
 
[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers
 
Connecting to Web Services on Android June 2 2010
Connecting to Web Services on Android June 2 2010Connecting to Web Services on Android June 2 2010
Connecting to Web Services on Android June 2 2010
 

Similar to Threads handlers and async task, widgets - day8

Asynchronous Programming in Android
Asynchronous Programming in AndroidAsynchronous Programming in Android
Asynchronous Programming in AndroidJohn Pendexter
 
Android application development
Android application developmentAndroid application development
Android application developmentMd. Mujahid Islam
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 ThreadingDiego Grancini
 
Presentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestatePresentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestateOsahon Gino Ediagbonya
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slidesDavid Barreto
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and threadMengChun Lam
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _courseDori Waldman
 
eFront V3.7 Extensions Architecture
eFront V3.7 Extensions ArchitectureeFront V3.7 Extensions Architecture
eFront V3.7 Extensions Architecturepapagel
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2Dori Waldman
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)Khaled Anaqwa
 
Case study on Movie Quiz App For IPhone and IPad – Facebook Enabled
Case study on Movie Quiz App For IPhone and IPad –  Facebook Enabled Case study on Movie Quiz App For IPhone and IPad –  Facebook Enabled
Case study on Movie Quiz App For IPhone and IPad – Facebook Enabled Grey Matter India Technologies PVT LTD
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operationMatteo Bonifazi
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycleKumar
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32Eden Shochat
 

Similar to Threads handlers and async task, widgets - day8 (20)

Asynchronous Programming in Android
Asynchronous Programming in AndroidAsynchronous Programming in Android
Asynchronous Programming in Android
 
Android application development
Android application developmentAndroid application development
Android application development
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
 
Android101
Android101Android101
Android101
 
Presentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestatePresentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestate
 
Android
AndroidAndroid
Android
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and thread
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
eFront V3.7 Extensions Architecture
eFront V3.7 Extensions ArchitectureeFront V3.7 Extensions Architecture
eFront V3.7 Extensions Architecture
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
 
Case study on Movie Quiz App For IPhone and IPad – Facebook Enabled
Case study on Movie Quiz App For IPhone and IPad –  Facebook Enabled Case study on Movie Quiz App For IPhone and IPad –  Facebook Enabled
Case study on Movie Quiz App For IPhone and IPad – Facebook Enabled
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
 
Fragment
Fragment Fragment
Fragment
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycle
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32
 

Recently uploaded

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Threads handlers and async task, widgets - day8

  • 1. 6/18/2013 1 Android Threading – Handlers and Async Tasks Android Widgets
  • 2. 6/18/2013 2 Processes and Threads in Android Processes By default, all components of the same application run in the same process and most applications should not change this. The manifest entry for each type of component element—<activity>, <service>, <receiver>, and <provider>— supports an android:process attribute that can specify a process in which that component should run. Threads When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events. The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread.
  • 3. 6/18/2013 3 Process lifecycle The Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes. To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components. There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is most important and is killed last): 1. Foreground process : A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true: • It hosts an Activity that the user is interacting with (the Activity's onResume() method has been called). • It hosts a Service that's bound to the activity that the user is interacting with. • It hosts a Service that's running "in the foreground"—the service has called startForeground(). • It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()). • It hosts a BroadcastReceiver that's executing its onReceive() method. Generally, only a few foreground processes exist at any given time. They are killed only as a last resort— if memory is so low that they cannot all continue to run.
  • 4. 6/18/2013 4 2. Visible process : A process that doesn't have any foreground components, but still can affect what the user sees on screen. A process is considered to be visible if either of the following conditions are true: • It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it. • It hosts a Service that's bound to a visible (or foreground) activity. A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running. 3. Service process : A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories. 4. Background process : A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. 5. Empty process : A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it.
  • 5. 6/18/2013 5 Thread Management Principles When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model: 1. Do not block the UI thread 2. Do not access the Android UI toolkit from outside the UI thread
  • 6. 6/18/2013 6 Thread Management using Handlers Because of the single thread model described above, it's vital to the responsiveness of your application's UI that you do not block the UI thread. If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads). public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork("http://example.com/image.png"); mImageView.setImageBitmap(b); } }).start(); } At first, this seems to work fine, because it creates a new thread to handle the network operation. However, it violates the second rule of the single-threaded model: do not access the Android UI toolkit from outside the UI thread—this sample modifies the ImageView from the worker thread instead of the UI thread. public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png"); mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); }
  • 7. 6/18/2013 7 Thread Management using AsyncTasks AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself. public void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png"); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { /** The system calls this to perform work in a worker thread and * delivers it the parameters given to AsyncTask.execute() */ protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); } } To use it, you must subclass AsyncTask and implement the doInBackground() callback method, which runs in a pool of background threads. To update your UI, you should implement onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your UI. You can then run the task by calling execute() from the UI thread.
  • 9. 6/18/2013 9 What is a Widget ? App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. The Basics of a widget : To create an App Widget, you need the following: AppWidgetProviderInfo object : Describes the metadata for an App Widget, such as the App Widget's layout, update frequency, and the AppWidgetProvider class. This should be defined in XML. AppWidgetProvider class implementation : Defines the basic methods that allow you to programmatically interface with the App Widget, based on broadcast events. Through it, you will receive broadcasts when the App Widget is updated, enabled, disabled and deleted. View layout : Defines the initial layout for the App Widget, defined in XML.
  • 10. 6/18/2013 10 Steps to Create a Widget Step 1 : Declaring the manifest <receiver android:name="ExampleAppWidgetProvider" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/example_appwidget_info" /> </receiver> The <receiver> element requires the android:name attribute, which specifies the AppWidgetProvider used by the App Widget. The <intent-filter> element must include an <action> element with the android:name attribute. This attribute specifies that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast that you must explicitly declare. The AppWidgetManager automatically sends all other App Widget broadcasts to the AppWidgetProvider as necessary. The <meta-data> element specifies the AppWidgetProviderInfo resource and requires the following attributes: 1. android:name - Specifies the metadata name. Use android.appwidget.provider to identify the data as the AppWidgetProviderInfo descriptor. 2. android:resource - Specifies the AppWidgetProviderInfo resource location.
  • 12. 6/18/2013 12 Step 4 : Writing the AppWidgetProvider class The AppWidgetProvider class extends BroadcastReceiver as a convenience class to handle the App Widget broadcasts. The AppWidgetProvider receives only the event broadcasts that are relevant to the App Widget, such as when the App Widget is updated, deleted, enabled, and disabled. onUpdate() : This is called to update the App Widget at intervals defined by the updatePeriodMillis attribute in the AppWidgetProviderInfo (see Adding the AppWidgetProviderInfo Metadata above). This method is also called when the user adds the App Widget, so it should perform the essential setup, such as define event handlers for Views and start a temporary Service, if necessary. However, if you have declared a configuration Activity, this method is not called when the user adds the App Widget, but is called for the subsequent updates. onAppWidgetOptionsChanged() : This is called when the widget is first placed and any time the widget is resized. You can use this callback to show or hide content based on the widget's size ranges.
  • 13. 6/18/2013 13 onDeleted(Context, int[]) : This is called every time an App Widget is deleted from the App Widget host. onEnabled(Context) : This is called when an instance the App Widget is created for the first time. For example, if the user adds two instances of your App Widget, this is only called the first time. If you need to open a new database or perform other setup that only needs to occur once for all App Widget instances, then this is a good place to do it. onDisabled(Context) : This is called when the last instance of your App Widget is deleted from the App Widget host. This is where you should clean up any work done in onEnabled(Context), such as delete a temporary database. onReceive(Context, Intent) : This is called for every broadcast and before each of the above callback methods. You normally don't need to implement this method because the default AppWidgetProvider implementation filters all App Widget broadcasts and calls the above methods as appropriate.
  • 14. 6/18/2013 14 Step 5 : Creating an App Widget Configuration Activity Defining the activity in the mainfest <activity android:name=".ExampleAppWidgetConfigure"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/> </intent-filter> </activity> 1. First, get the App Widget ID from the Intent that launched the Activity: 2. Perform your App Widget configuration. 3. When the configuration is complete, get an instance of the AppWidgetManager by calling getInstance(Context): 4. Finally, create the return Intent, set it with the Activity result, and finish the Activity:
  • 15. 6/18/2013 15 Step 6 : Enabling App Widgets on the Lockscreen and Setting the Preview image Android 4.2 introduces the ability for users to add widgets to the lock screen. To indicate that your app widget is available for use on the lock screen, declare the android:widgetCategory attribute in the XML file that specifies your AppWidgetProviderInfo. <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" ... android:widgetCategory="keyguard|home_screen"> </appwidget-provider>