Android development training programme , Day 3

3,144 views
3,100 views

Published on

This

1 Comment
2 Likes
Statistics
Notes
  • This document contains the Threads in Android , Services with a simple examples and the techniques .. Follow us on Linked in

    http://www.linkedin.com/groups/Android-ios-BlackBerry-Mobile-Masters-4512117?home=&gid=4512117&trk=anet_ug_hm
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
3,144
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
67
Comments
1
Likes
2
Embeds 0
No embeds

No notes for slide

Android development training programme , Day 3

  1. 1. Android development Training programme Day 3 17/11/2012 Dhiraj Karalkar
  2. 2. 2Day 3Session 1 Background Processing in an Android ThreadsAndroid supports the usage of the Threads class to perform asynchronous processing.Android also supplies the java.util.concurrent package to perform something in the background, e.g.using the ThreadPools and Executor classes.If you need to update the user interface from a new Thread, you need to synchronize with the userinterface thread.You can use the android.os.Handler class or the AsyncTasks class for this. HandlerThe Handler class can update the user interface. A Handler provides methods for receiving instances ofthe Message or Runnable class.To use a handler you have to subclass it and override the handleMessage() to process messages. Toprocess a Runnable you can use the post() method. You only need one instance of a Handler in yourActivity.You thread can post messages via the sendMessage(Message msg) method or via thesendEmptyMessage() method. AsyncTaskThe AsyncTask class encapsulates the creation of Threads and Handlers. An AsyncTask is started viathe execute() method.The execute() method calls the doInBackground() and the onPostExecute() method.The doInBackground() method contains the coding instruction which should be performed in abackground thread.This method runs automatically in a separate Thread.The onPostExecute() method synchronize itself again with the user interface thread and allows to updateit.This method is called by the framework once the doInBackground() method finishes.To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are thefollowing AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used forprogress information and ResultValue must be returned from doInBackground() method and is passed toonPostExecute() as parameter. @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  3. 3. 3 Handler with ExampleA Handler allows you to send and process Message and Runnable objects associated with a threadsMessageQueue. Each Handler instance is associated with a single thread and that threads message queue.When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them asthey come out of the message queue.How do the 2 threads (parent/UI and the worker threads) communicate? Here comes the Handler. Bydefinition – “A Handler allows you to send and process Message and Runnable objects associated with athreads MessageQueue. Each Handler instance is associated with a single thread and that threadsmessage queue.”So, let us take the handler from the main thread and see how we can use it to communicate with a childthread.When a handler is created, it is associated by default with the current thread. So, we have this piece ofcode in the main activity class:Now, I spawn a new thread through a method that is called when I click a button. So, let us see thebutton piece of code first:Here I am providing the xml layout and the HandlerActivity source code for the button click event @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  4. 4. 4Here is the piece of code where the Handler is initializedNow, on click of the button, the fetchData() method is invoked.Since it is time consuming, I am starting a ProgressDialog just to inform the end user that some activity ishappening. Then, I start the thread, make it sleep for 800 milliseconds and send back an empty messagethrough the message handler. The messageHandler.sendEmptyMessage(0) is the callback on the parentthread’s messageHandler to inform that the child thread has finished its work. In this example I amsending an empty message. But this can be the means of communication and exchange of data from thechild thread to the parent Thread.Now the control returns to handleMessage() call back method. That method shown in the beginning justdismisses the progressDialog.In real life cases, within this thread we can do things like calling web-services, calling web-sites to fetchspecific data or doing network IO operations and returning actual data that needs to be displayed on thefront-end.0 @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  5. 5. 5 AsyncTask with ExampleAsyncTask enables proper and easy use of the UI thread. This class allows to perform backgroundoperations and publish results on the UI thread without having to manipulate threads and/or handlers.The AsyncTask class encapsulates the creation of Threads and Handlers. An AsyncTask is started via theexecute() method.The execute() method calls the doInBackground() and the onPostExecute() method.The doInBackground() method contains the coding instruction which should be performed in abackground thread. This method runs automatically in a separate Thread.The onPostExecute() method synchronize itself again with the user interface thread and allows to updateit. This method is called by the framework once the doInBackground() method finishes.To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are thefollowing AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used forprogress information and ResultValue must be returned from doInBackground() method and is passed toonPostExecute() as parameter.In this example we will use an instance of the AsyncTask class to download the content of a webpage.We use Android HttpClient for this. Create a new Android project called ThreadAsynkTaskExamplewith an Activity called ThreadAsynkTaskActivity. Add the android.permission.INTERNET permissionto your <filenname>AndroidManifest.xml</filenname> file. .Create the following layout.On the buttonClick we are executing the AsynkTask WebPageDownloadTask as task.execute() @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  6. 6. 6Following is the AsynkTask in our scenario the WebPageDownLoadTask is extendingAsyncTask<String, Void, String> of android.os.AsyncTask packageThis WebPageDownLoadTask contains the overridden method of the AsynksTask i) onPreExecute() : in this method we are started the the Progress bar ii) doInBackground(String... urls): in the doInBackground we have a logic of downloading the text from the specific url iii) onPostExecute(String result): In this method we are dismissing the ProgressBar and adding text to the TextViewHere is the source code for the SameIf you run your application and press your button then the content of the defined webpage should beread in the background. Once this process is done your TextView will be updated. @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  7. 7. 7Session2 Broadcast ReceiversThe concept of Broadcast Receivers, one of the fundamental blocks of Android, is very simple. These areapplications that will respond to any intent that is broadcast by other applications. Provided thebroadcast intent matches the intent specified against the receiver in the AndroidManifest.xmlThis goes to automatically imply that many activities, events, services or the like can broadcast intentsexpecting the appropriate action to be automatically taken. So, to begin with, let us see the variousBroadcast events that are given by the platform itself. Here is a standard list obtained from the androiddocumentation:  ACTION_TIME_TICK  ACTION_TIME_CHANGED  ACTION_TIMEZONE_CHANGED  ACTION_BOOT_COMPLETED  ACTION_PACKAGE_ADDED  ACTION_PACKAGE_CHANGED  ACTION_PACKAGE_REMOVED  ACTION_PACKAGE_RESTARTED  ACTION_PACKAGE_DATA_CLEARED  ACTION_UID_REMOVED  ACTION_BATTERY_CHANGED  ACTION_POWER_CONNECTED  ACTION_POWER_DISCONNECTED  ACTION_SHUTDOWNWe will define a broadcast receiver which listens to telephone state changes. If the phone receives aphone call then our receiver will be notified and log a message.Here is the manifest file for the BroadCastReceiver Example , You must register the receiver as shown inthe following code @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  8. 8. 8Here is the MyBroadcastReceiver extending BroadcastReceiver class , when any Telephony call arrivedand disconnected then the onReceive(Context context, Intent intent) get called .You can even register BroadcastReceiver progrmatically by usingContext.registerReceiver(BroadCastReceiver bcr, IntentFilter ifilter );To view the output of this application , install this application in your mobile Phone and make a call theBroadcastReceiver gets called @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  9. 9. 9Session 3Understanding Services in androidRole of servicesService life cycle methods What is service ?A Service is an application component representing either an applications desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications touse. Each service class must have a corresponding <service> declaration in its packagesAndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().If user wants to create a longer background action like Playing the songs even if your activity is closed ,or to download some files from the server in the background then Service used to do the Backgroundprocesses without having UI ..To create an application to run in the background of other current activities, one needs to create a Service.The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).Please note that a Service has a different lifecycle than activities therefore have different methods. But tobegin a service in the application a call to startService() which envokes the service onCreate() method andonStart() beginning running the service.context.startService() | ->onCreate() - >onStartCommand() [service running]Calling the applications stopService() method to stop the service.context.stopService() | ->onDestroy() [service stops]Something that we didnt use in this example is bindService() which just calls the services onCreate()method but does not call the onStartCommand(). onBindService() is used to create persistanceconnection to the service.context.onBindService() | ->onCreate() [service created] @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  10. 10. 10 Service ExampleThis Services Demo is simple as it plays an audio file and by listening to click events of the buttonsinvokes the MyService service.Add any of the audio file to your res >> raw folder of an applicationNote : you must add the following tag in the manifest file to register your service<service android:enabled="true" android:name="MyService" />Layout file : activity_service_demo.xmlHere is your ServicesDemo which extends Activity and implements OnClickListener @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  11. 11. 11When the user clicks on the start Button then startService() method gets called which invokes yourMyService’s onCreate() method , in this method we have initialize the MediaPlayer right now for thisignore the Functionality of the Media player just concentrate on the Service .After that the OnStart() method get called of the MyService where we have started the Media PlayerYour service is started now even if you close your activity the service will run in the Background , that isthe basic use of using the Service in Android .Now to stop the media file you need to stop the service , refer the ServicesDemo above ,Onclicking the stopbutton the stopService() method gets called which stops your service running in thebackground , this stopService() method calls the onDestroy() method of the MyServiceWhich stops the service running in the BackgroundHere is the code to start your service (here MyService)which plays an audio file in a background @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com

×