15
27/08/22 1 Android Threading – Handlers and Async Tasks Android Widgets

Threads handlers and async task, widgets - day8

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Threads   handlers and async task, widgets - day8

18-06-2013 1

Android Threading – Handlers and Async TasksAndroid Widgets

Page 2: Threads   handlers and async task, widgets - day8

18-06-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.

Page 3: Threads   handlers and async task, widgets - day8

18-06-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.

Page 4: Threads   handlers and async task, widgets - day8

18-06-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.

Page 5: Threads   handlers and async task, widgets - day8

18-06-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 thread2. Do not access the Android UI toolkit from outside the UI thread

Page 6: Threads   handlers and async task, widgets - day8

18-06-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();}

Page 7: Threads   handlers and async task, widgets - day8

18-06-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.

Page 8: Threads   handlers and async task, widgets - day8

18-06-2013 8

Android Widgets

Page 9: Threads   handlers and async task, widgets - day8

18-06-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.

Page 10: Threads   handlers and async task, widgets - day8

18-06-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.

Page 11: Threads   handlers and async task, widgets - day8

18-06-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

Page 12: Threads   handlers and async task, widgets - day8

18-06-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.

Page 13: Threads   handlers and async task, widgets - day8

18-06-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.

Page 14: Threads   handlers and async task, widgets - day8

18-06-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:

Page 15: Threads   handlers and async task, widgets - day8

18-06-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>