Threads handlers and async task, widgets - day8

1,387 views

Published on

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,387
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
27
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Threads handlers and async task, widgets - day8

  1. 1. 6/18/2013 1Android Threading – Handlers and Async TasksAndroid Widgets
  2. 2. 6/18/2013 2Processes and Threads in AndroidProcessesBy default, all components of the same application run in the same process and most applications should notchange 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.ThreadsWhen 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 interfacewidgets, including drawing events.The system does not create a separate thread for each instance of a component. All components that run inthe same process are instantiated in the UI thread, and system calls to each component are dispatched fromthat thread.
  3. 3. 6/18/2013 3Process lifecycleThe Android system tries to maintain an application process for as long as possible, but eventually needs toremove old processes to reclaim memory for new or more important processes. To determine whichprocesses to keep and which to kill, the system places each process into an "importance hierarchy" based onthe 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 processesin 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 isconsidered to be in the foreground if any of the following conditions are true:• It hosts an Activity that the user is interacting with (the Activitys onResume() method has beencalled).• It hosts a Service thats bound to the activity that the user is interacting with.• It hosts a Service thats running "in the foreground"—the service has called startForeground().• It hosts a Service thats executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).• It hosts a BroadcastReceiver thats 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. 4. 6/18/2013 42. Visible process : A process that doesnt have any foreground components, but still can affect what the usersees 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 hasbeen called). This might occur, for example, if the foreground activity started a dialog, which allows theprevious activity to be seen behind it.• It hosts a Service thats 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 allforeground processes running.3. Service process : A process that is running a service that has been started with the startService() method anddoes not fall into either of the two higher categories.4. Background process : A process holding an activity thats not currently visible to the user (the activitysonStop() method has been called). These processes have no direct impact on the user experience, and thesystem can kill them at any time to reclaim memory for a foreground, visible, or service process.5. Empty process : A process that doesnt hold any active application components. The only reason to keep thiskind of process alive is for caching purposes, to improve startup time the next time a component needs to runin it.
  5. 5. 6/18/2013 5Thread Management PrinciplesWhen your app performs intensive work in response to user interaction, this single thread model can yieldpoor performance unless you implement your application properly. Specifically, if everything is happening inthe 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 workerthread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply tworules to Androids single thread model:1. Do not block the UI thread2. Do not access the Android UI toolkit from outside the UI thread
  6. 6. 6/18/2013 6Thread Management using HandlersBecause of the single thread model described above, its vital to the responsiveness of your applications UIthat you do not block the UI thread. If you have operations to perform that are not instantaneous, you shouldmake 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 networkoperation. However, it violates the second rule of the single-threaded model: do not accessthe Android UI toolkit from outside the UI thread—this sample modifies the ImageViewfrom 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. 7. 6/18/2013 7Thread Management using AsyncTasksAsyncTask allows you to perform asynchronous work on your user interface. It performs the blockingoperations in a worker thread and then publishes the results on the UI thread, without requiring you to handlethreads 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 apool of background threads. To update your UI, you should implement onPostExecute(), which delivers the resultfrom doInBackground() and runs in the UI thread, so you can safely update your UI. You can then run the task bycalling execute() from the UI thread.
  8. 8. 6/18/2013 8Android Widgets
  9. 9. 6/18/2013 9What is a Widget ?App Widgets are miniature application views that can be embedded in other applications (such as the Homescreen) 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 Widgets layout,update frequency, and the AppWidgetProvider class. This should be defined in XML.AppWidgetProvider class implementation : Defines the basic methods that allow you to programmaticallyinterface with the App Widget, based on broadcast events. Through it, you will receive broadcasts when theApp Widget is updated, enabled, disabled and deleted.View layout : Defines the initial layout for the App Widget, defined in XML.
  10. 10. 6/18/2013 10Steps to Create a WidgetStep 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 AppWidget.The <intent-filter> element must include an <action> element with the android:name attribute. This attribute specifiesthat the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast that you mustexplicitly declare. The AppWidgetManager automatically sends all other App Widget broadcasts to the AppWidgetProvideras 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 theAppWidgetProviderInfo descriptor.2. android:resource - Specifies the AppWidgetProviderInfo resource location.
  11. 11. 6/18/2013 11<appwidget-providerxmlns: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 layoutYou must define an initial layout for your App Widget in XML and save it in the projects res/layout/ directory.You can design your App Widget using the View objects
  12. 12. 6/18/2013 12Step 4 : Writing the AppWidgetProvider classThe AppWidgetProvider class extends BroadcastReceiver as a convenience class to handle the App Widgetbroadcasts. The AppWidgetProvider receives only the event broadcasts that are relevant to the App Widget, such aswhen the App Widget is updated, deleted, enabled, and disabled.onUpdate() : This is called to update the App Widget at intervals defined by the updatePeriodMillis attributein the AppWidgetProviderInfo (see Adding the AppWidgetProviderInfo Metadata above). This method is alsocalled when the user adds the App Widget, so it should perform the essential setup, such as define eventhandlers for Views and start a temporary Service, if necessary. However, if you have declared a configurationActivity, this method is not called when the user adds the App Widget, but is called for the subsequentupdates.onAppWidgetOptionsChanged() : This is called when the widget is first placed and any time the widgetis resized. You can use this callback to show or hide content based on the widgets size ranges.
  13. 13. 6/18/2013 13onDeleted(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 newdatabase or perform other setup that only needs to occur once for all App Widget instances, then this is a goodplace to do it.onDisabled(Context) : This is called when the last instance of your App Widget is deleted from the App Widgethost. This is where you should clean up any work done in onEnabled(Context), such as delete a temporarydatabase.onReceive(Context, Intent) : This is called for every broadcast and before each of the above callback methods.You normally dont need to implement this method because the default AppWidgetProvider implementationfilters all App Widget broadcasts and calls the above methods as appropriate.
  14. 14. 6/18/2013 14Step 5 : Creating an App Widget Configuration ActivityDefining 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 callinggetInstance(Context):4. Finally, create the return Intent, set it with the Activity result, and finish the Activity:
  15. 15. 6/18/2013 15Step 6 : Enabling App Widgets on the Lockscreen and Setting the Preview imageAndroid 4.2 introduces the ability for users to add widgets to the lock screen. To indicate that your app widget isavailable for use on the lock screen, declare the android:widgetCategory attribute in the XML file that specifiesyour AppWidgetProviderInfo.<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"...android:widgetCategory="keyguard|home_screen"></appwidget-provider>

×