33
Lecture 6 SERVICES & THREADING IN ANDROID

Lecture 6 Threading

Embed Size (px)

Citation preview

Lecture 6SERVICES & THREADING IN ANDROID

Threading •Process is a program unit of execution.

–Independent on each others

–Different resources allocated, no shared memory

–May contain multiple threads

•Thread is kind a lightweight processes

–Threads share memory space and resources

–Lower effort required to create new thread rather than new process

More About :

http://developer.android.com/guide/components/processes-and-threads.html

Why Threads •advantages

–Better performance especially in multi-CPU environment

–Efficiency

–Responsiveness

•disadvantage

–Hard to debug and maintain

–Require some extra work for the management of shared resources and synchronization

Concurrency issues •Thread can change data while others don’t see that change. No response problem

•Shared data problem when several thread trying to access and change the same shared data at the same time. In correct data and behaviour

Synchronization and mutual exclusive access

•Synchronized Key word

–Ensure that only a single thread can execute a block of code at the same time

•Mark your method or code block as synchronized

public synchronized void myMethod()

{

}

Synchronization and mutual exclusive access

•Volatile keyword

–Indicates that a variable's value will be modified by different threads.

–Ensure that the value of this variable will never be cached thread-locally.

–Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

Source :

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Making Threads •Creating New Threads

–Implementing Runnable

–Extending Thread class

•In Android , you may

–Make Separate class implements runnable

–Make the main activity implements runnable

–Create different class extends thread

Implementing Runnable class MyRunnableObject implements Runnable {

public void run ()

{

//do thread work here }

}

Extending Thread Class public class MyRunnable2 extends Thread {

public void run()

{

//Thread Code here

}

}

Starting threads:

threadName.Start();

More readings about threads •http://www.javamex.com/tutorials/threads/

•http://docs.oracle.com/javase/tutorial/essential/concurrency

•http://www.vogella.com/articles/JavaConcurrency/article.html#concurrency_processthreads

Services in Android •A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

•There are two types of service components

–Started (Un-Bounded)

–Bounded

Service Types •Started (Un-Bounded) :

–This service is started using the startService() Method. Once started it keeps running until someone stops the service or stops itself stopself().

•Bounded:

–This service is started using bindService() method.

–Service binding is used to perform client-server like communication between the service and the caller.

Example 1: Playing Audio Files •Add the media file to res/raw folder

•Implement a class that extends service

–Override onStart() and add the code to start playing the audio file

–Override onDestrory() and add the code to stop playing the audio file

–Add Service declaration to the Manifest

<service android:name=“com.pack.example.myservice”></service>

Aside : Raw Folder VS. Assets Folder

•To save some files (e.g. audio files or tones) in your application you have two options:

–res/raw and,

–assets

•Raw Folder

–Precompiled generated id for resources

•Assets Folder

–Behave like a file system

–Can be listed and iterated easily with AssetManager class

Using the service

Bound Services •A bound service is the server in a client-server interface.

•A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC).

•A bound service typically lives only while it serves another application component and does not run in the background indefinitely.

Bound Service Example : Extending Binder Class

Bound Service Example : Extending Binder Class

public class LocalBinder extends Binder

{ Public LocalService getService() { // Return this instance of LocalService so clients can call public methods return LocalService.this; }

}

•Source:

–http://developer.android.com/guide/components/bound-services.html

Bound Service Example (cont.) : Binding

ServiceConnection conn = new ServiceConnection()

{ @Override public void onServiceConnected(ComponentName name, IBinder service) { // when connected do this @Override public void onServiceDisconnected(ComponentName arg0) { // when disconnected do this }

}

bindService(new Intent(“net.ov.apps.MY_SERVICE"), conn);

See more http://developer.android.com/guide/components/bound-services.html

Intent Services

Service, Thread and IntentService

•The service itself run in the same process, not in separate thread. So if the background service do intensive processing, it may badly affect the performance and make the application not responding.

•Solutions:

–Implement the code represents the service work in a separate worker thread

OR

–Extend IntentService instead of Service class

Difference between Service and IntentService

•Service

–uses application main thread.

–needs a manual stop using stop() or stopSelf()

–android:process=":process_description“ can be used to make it in a separate process.

•IntentService:

–handle asynchronous requests (expressed as Intents) on demand.

–handles each Intent in turn by creating a worker thread, and stops itself when it runs out of work.

–automatically stops itself when there is no intent in queue.

Note : •You can also specify that your Service runs in a separate process via the android:process=":process_description" attribute.

•This way the service gets its own process and has its own memory. Any long running operation in theService, e.g. a garbage collection, will not affect the user interface of your Activity

Services with Broadcasts •Objective

–We need to update the UI Thread with information coming from a background service.

•Approach

–Implement an inner broadcast receiver in the main activity that is , when receiving a message, updates the UI.

–In the background service, send a broadcast message “Intent” holding the necessary data for the UI

Using AsyncTask •Another technique in android for running back ground services easily.

•Enables proper and easy use of the UI thread.

•This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Using AsyncTask

asynchronous task implementation

•onPreExecute()

–invoked on the UI thread immediately after the task is executed.

–Setup the task here, for instance by show a progress bar in the user interface.

asynchronous task implementation

•doInBackground(Params...)

–invoked on the background thread immediately after onPreExecute() finishes executing.

–This step is used to perform background computation that can take a long time.

–The parameters of the asynchronous task are passed to this step.

–This step can also use publishProgress(Progress...)to publish one or more units of progress.

–These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

asynchronous task implementation

•onProgressUpdate(Progress...),

–invoked on the UI thread after a call to publishProgress(Progress...).

–This method is used to display any form of progress in the user interface while the background computation is still executing.

asynchronous task implementation

•onPostExecute(Result)

–invoked on the UI thread after the background computation finishes.

–The result of the background computation is passed to this step as a parameter.

Start Process Automatically When System Boots

•To start Services automatically after the Android system starts you can register a BroadcastReceiver to the Android

android.intent.action.BOOT_COMPLETED system event.

This requires the

android.permission.RECEIVE_BOOT_COMPLETED permission.

•Source: http://www.vogella.com/articles/AndroidServices/article.html

More About Services –http://saigeethamn.blogspot.com/search?q=service

–http://www.anddev.org/remote_service_tutorial-t8127.html

–http://www.androidcompetencycenter.com/2009/01/basics-of-android-part-iii-android-services/