Top Banner
Lecture 6 SERVICES & THREADING IN ANDROID
33
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lecture 6 Threading

Lecture 6SERVICES & THREADING IN ANDROID

Page 2: Lecture 6 Threading

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

Page 3: Lecture 6 Threading

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

Page 4: Lecture 6 Threading

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

Page 5: Lecture 6 Threading

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

{

}

Page 6: Lecture 6 Threading

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

Page 7: Lecture 6 Threading

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

Page 8: Lecture 6 Threading

Implementing Runnable class MyRunnableObject implements Runnable {

public void run ()

{

//do thread work here }

}

Page 9: Lecture 6 Threading

Extending Thread Class public class MyRunnable2 extends Thread {

public void run()

{

//Thread Code here

}

}

Starting threads:

threadName.Start();

Page 10: Lecture 6 Threading

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

Page 11: Lecture 6 Threading

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

Page 12: Lecture 6 Threading

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.

Page 13: Lecture 6 Threading
Page 14: Lecture 6 Threading

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>

Page 15: Lecture 6 Threading

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

Page 16: Lecture 6 Threading

Using the service

Page 17: Lecture 6 Threading

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.

Page 18: Lecture 6 Threading

Bound Service Example : Extending Binder Class

Page 19: Lecture 6 Threading

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

Page 20: Lecture 6 Threading

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

Page 21: Lecture 6 Threading

Intent Services

Page 22: Lecture 6 Threading

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

Page 23: Lecture 6 Threading

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.

Page 24: Lecture 6 Threading

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

Page 25: Lecture 6 Threading

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

Page 26: Lecture 6 Threading

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.

Page 27: Lecture 6 Threading

Using AsyncTask

Page 28: Lecture 6 Threading

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.

Page 29: Lecture 6 Threading

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.

Page 30: Lecture 6 Threading

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.

Page 31: Lecture 6 Threading

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.

Page 32: Lecture 6 Threading

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

Page 33: Lecture 6 Threading

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/