SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Downloaden Sie, um offline zu lesen
Android development Training
         programme
             Day 3
           17/11/2012

          Dhiraj Karalkar
2



Day 3
Session 1
                          Background Processing in an Android

                                              Threads

Android 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 user
interface thread.

You can use the android.os.Handler class or the AsyncTasks class for this.
                                               Handler

The Handler class can update the user interface. A Handler provides methods for receiving instances of
the Message or Runnable class.
To use a handler you have to subclass it and override the handleMessage() to process messages. To
process a Runnable you can use the post() method. You only need one instance of a Handler in your
Activity.
You thread can post messages via the sendMessage(Message msg) method or via the
sendEmptyMessage() method.
                                             AsyncTask

The AsyncTask class encapsulates the creation of Threads and Handlers. An AsyncTask is started via
the execute() method.
The execute() method calls the doInBackground() and the onPostExecute() method.
The doInBackground() method contains the coding instruction which should be performed in a
background thread.
This method runs automatically in a separate Thread.
The onPostExecute() method synchronize itself again with the user interface thread and allows to update
it.
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 the
following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for
progress information and ResultValue must be returned from doInBackground() method and is passed to
onPostExecute() as parameter.




                    @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
3


                                      Handler with Example

A Handler allows you to send and process Message and Runnable objects associated with a thread's
MessageQueue. Each Handler instance is associated with a single thread and that thread's 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 as
they come out of the message queue.

How do the 2 threads (parent/UI and the worker threads) communicate? Here comes the Handler. By
definition – “A Handler allows you to send and process Message and Runnable objects associated with a
thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's
message queue.”

So, let us take the handler from the main thread and see how we can use it to communicate with a child
thread.

When a handler is created, it is associated by default with the current thread. So, we have this piece of
code 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 the
button 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




Here is the piece of code where the Handler is initialized




Now, 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 is
happening. Then, I start the thread, make it sleep for 800 milliseconds and send back an empty message
through the message handler. The messageHandler.sendEmptyMessage(0) is the callback on the parent
thread’s messageHandler to inform that the child thread has finished its work. In this example I am
sending an empty message. But this can be the means of communication and exchange of data from the
child thread to the parent Thread.

Now the control returns to handleMessage() call back method. That method shown in the beginning just
dismisses the progressDialog.

In real life cases, within this thread we can do things like calling web-services, calling web-sites to fetch
specific data or doing network IO operations and returning actual data that needs to be displayed on the
front-end.0




                     @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
5


                                    AsyncTask with Example

AsyncTask 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.

The AsyncTask class encapsulates the creation of Threads and Handlers. An AsyncTask is started via the
execute() method.
The execute() method calls the doInBackground() and the onPostExecute() method.
The doInBackground() method contains the coding instruction which should be performed in a
background thread. This method runs automatically in a separate Thread.
The onPostExecute() method synchronize itself again with the user interface thread and allows to update
it. 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 the
following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for
progress information and ResultValue must be returned from doInBackground() method and is passed to
onPostExecute() 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 ThreadAsynkTaskExample
with an Activity called ThreadAsynkTaskActivity. Add the android.permission.INTERNET permission
to 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



Following is the AsynkTask in our scenario the WebPageDownLoadTask is extending
AsyncTask<String, Void, String> of android.os.AsyncTask package
This 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 TextView

Here is the source code for the Same




If you run your application and press your button then the content of the defined webpage should be
read in the background. Once this process is done your TextView will be updated.




                    @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
7



Session2
                                       Broadcast Receivers
The concept of Broadcast Receivers, one of the fundamental blocks of Android, is very simple. These are
applications that will respond to any intent that is broadcast by other applications. Provided the
broadcast intent matches the intent specified against the receiver in the AndroidManifest.xml

This goes to automatically imply that many activities, events, services or the like can broadcast intents
expecting the appropriate action to be automatically taken. So, to begin with, let us see the various
Broadcast events that are given by the platform itself. Here is a standard list obtained from the android
documentation:

       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_SHUTDOWN

We will define a broadcast receiver which listens to telephone state changes. If the phone receives a
phone 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 in
the following code




                    @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
8




Here is the MyBroadcastReceiver extending BroadcastReceiver class , when any Telephony call arrived
and disconnected then the onReceive(Context context, Intent intent) get called .




You can even register BroadcastReceiver progrmatically by using

Context.registerReceiver(BroadCastReceiver bcr, IntentFilter ifilter );

To view the output of this application , install this application in your mobile Phone and make a call the
BroadcastReceiver gets called




                     @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
9



Session 3
Understanding Services in android
Role of services
Service life cycle methods


                                          What is service ?

A Service is an application component representing either an application's desire to perform a longer-
running operation while not interacting with the user or to supply functionality for other applications to
use. Each service class must have a corresponding <service> declaration in its package's
AndroidManifest.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 Background
processes 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 to
begin a service in the application a call to startService() which envokes the service onCreate() method and
onStart() 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 didn't use in this example is bindService() which just calls the services onCreate()
method but does not call the onStartCommand(). onBindService() is used to create persistance
connection to the service.

context.onBindService() | ->onCreate() [service created]




                     @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
10


                                          Service Example

This Services Demo is simple as it plays an audio file and by listening to click events of the buttons
invokes the MyService service.
Add any of the audio file to your res >> raw folder of an application
Note : 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.xml




Here is your ServicesDemo which extends Activity and implements OnClickListener




                     @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
11



When the user clicks on the start Button then startService() method gets called which invokes your
MyService’s onCreate() method , in this method we have initialize the MediaPlayer right now for this
ignore 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 Player
Your service is started now even if you close your activity the service will run in the Background , that is
the 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 the
background , this stopService() method calls the onDestroy() method of the MyService
Which stops the service running in the Background

Here 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

Weitere ähnliche Inhalte

Was ist angesagt?

Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#Rizwan Ali
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Sachintha Gunasena
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 ThreadingDiego Grancini
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization ConstructsSasha Kravchuk
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 

Was ist angesagt? (20)

Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Tech talk
Tech talkTech talk
Tech talk
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
java threads
java threadsjava threads
java threads
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 

Andere mochten auch

Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentationconnectshilpa
 
Deep dive into Android async operations
Deep dive into Android async operationsDeep dive into Android async operations
Deep dive into Android async operationsMateusz Grzechociński
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Androidcoolmirza143
 
Introduction to Mobile Technology
Introduction to Mobile TechnologyIntroduction to Mobile Technology
Introduction to Mobile TechnologyPriya Nath
 
10 ways to improve your Android app performance
10 ways to improve your Android app performance10 ways to improve your Android app performance
10 ways to improve your Android app performanceBoris Farber
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
Mobile Android and Network
Mobile Android and NetworkMobile Android and Network
Mobile Android and NetworkPadma Sankar
 
Android Operating System
Android Operating System Android Operating System
Android Operating System Sunil Maurya
 
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan KuštInfinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan KuštInfinum
 
Infinum Android Talks #13 - Design Support Library by Ivan Markusi
Infinum Android Talks #13 - Design Support Library by Ivan MarkusiInfinum Android Talks #13 - Design Support Library by Ivan Markusi
Infinum Android Talks #13 - Design Support Library by Ivan MarkusiInfinum
 
Introduction To Model View Presenter
Introduction To Model View PresenterIntroduction To Model View Presenter
Introduction To Model View Presentersaeed shargi ghazani
 
Android development Training Programme Day 2
Android development Training Programme Day 2Android development Training Programme Day 2
Android development Training Programme Day 2DHIRAJ PRAVIN
 
Android development training programme Day 1
Android development training programme Day 1Android development training programme Day 1
Android development training programme Day 1DHIRAJ PRAVIN
 
Android development - Network Requests
Android development - Network RequestsAndroid development - Network Requests
Android development - Network RequestsLope Emano
 

Andere mochten auch (20)

Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
 
Android ppt
Android ppt Android ppt
Android ppt
 
Deep dive into Android async operations
Deep dive into Android async operationsDeep dive into Android async operations
Deep dive into Android async operations
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Android
 
Introduction to Mobile Technology
Introduction to Mobile TechnologyIntroduction to Mobile Technology
Introduction to Mobile Technology
 
10 ways to improve your Android app performance
10 ways to improve your Android app performance10 ways to improve your Android app performance
10 ways to improve your Android app performance
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Intro to mobile technology
Intro to mobile technologyIntro to mobile technology
Intro to mobile technology
 
Mobile Android and Network
Mobile Android and NetworkMobile Android and Network
Mobile Android and Network
 
Android HTTP Service
Android HTTP ServiceAndroid HTTP Service
Android HTTP Service
 
Android Operating System
Android Operating System Android Operating System
Android Operating System
 
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan KuštInfinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
 
Infinum Android Talks #13 - Design Support Library by Ivan Markusi
Infinum Android Talks #13 - Design Support Library by Ivan MarkusiInfinum Android Talks #13 - Design Support Library by Ivan Markusi
Infinum Android Talks #13 - Design Support Library by Ivan Markusi
 
Introduction To Model View Presenter
Introduction To Model View PresenterIntroduction To Model View Presenter
Introduction To Model View Presenter
 
Android development Training Programme Day 2
Android development Training Programme Day 2Android development Training Programme Day 2
Android development Training Programme Day 2
 
ButterKnife
ButterKnifeButterKnife
ButterKnife
 
Android development training programme Day 1
Android development training programme Day 1Android development training programme Day 1
Android development training programme Day 1
 
Android development - Network Requests
Android development - Network RequestsAndroid development - Network Requests
Android development - Network Requests
 
What's Parse
What's ParseWhat's Parse
What's Parse
 

Ähnlich wie Android development training programme , Day 3

Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfEngmohammedAlzared
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESOBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESsuthi
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Android async task
Android async taskAndroid async task
Android async taskMadhu Venkat
 
Android async task
Android async taskAndroid async task
Android async taskMadhu Venkat
 
Analysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMSAnalysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMSPVS-Studio
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 
Graphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLetsGraphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLetsJussi Pohjolainen
 
Mobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfMobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfAbdullahMunir32
 

Ähnlich wie Android development training programme , Day 3 (20)

Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 
Android session-5-sajib
Android session-5-sajibAndroid session-5-sajib
Android session-5-sajib
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESOBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
manual
manualmanual
manual
 
manual
manualmanual
manual
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Android async task
Android async taskAndroid async task
Android async task
 
Android async task
Android async taskAndroid async task
Android async task
 
ReactJS.pptx
ReactJS.pptxReactJS.pptx
ReactJS.pptx
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
 
Smart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
 
Analysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMSAnalysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMS
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Graphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLetsGraphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLets
 
Mobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfMobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdf
 
Concurrency and parallel in .net
Concurrency and parallel in .netConcurrency and parallel in .net
Concurrency and parallel in .net
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Learn Drupal 8 Render Pipeline
Learn Drupal 8 Render PipelineLearn Drupal 8 Render Pipeline
Learn Drupal 8 Render Pipeline
 

Android development training programme , Day 3

  • 1. Android development Training programme Day 3 17/11/2012 Dhiraj Karalkar
  • 2. 2 Day 3 Session 1 Background Processing in an Android Threads Android 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 user interface thread. You can use the android.os.Handler class or the AsyncTasks class for this. Handler The Handler class can update the user interface. A Handler provides methods for receiving instances of the Message or Runnable class. To use a handler you have to subclass it and override the handleMessage() to process messages. To process a Runnable you can use the post() method. You only need one instance of a Handler in your Activity. You thread can post messages via the sendMessage(Message msg) method or via the sendEmptyMessage() method. AsyncTask The AsyncTask class encapsulates the creation of Threads and Handlers. An AsyncTask is started via the execute() method. The execute() method calls the doInBackground() and the onPostExecute() method. The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread. The onPostExecute() method synchronize itself again with the user interface thread and allows to update it. 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 the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> . TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as parameter. @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  • 3. 3 Handler with Example A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's 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 as they come out of the message queue. How do the 2 threads (parent/UI and the worker threads) communicate? Here comes the Handler. By definition – “A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.” So, let us take the handler from the main thread and see how we can use it to communicate with a child thread. When a handler is created, it is associated by default with the current thread. So, we have this piece of code 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 the button 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 Here is the piece of code where the Handler is initialized Now, 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 is happening. Then, I start the thread, make it sleep for 800 milliseconds and send back an empty message through the message handler. The messageHandler.sendEmptyMessage(0) is the callback on the parent thread’s messageHandler to inform that the child thread has finished its work. In this example I am sending an empty message. But this can be the means of communication and exchange of data from the child thread to the parent Thread. Now the control returns to handleMessage() call back method. That method shown in the beginning just dismisses the progressDialog. In real life cases, within this thread we can do things like calling web-services, calling web-sites to fetch specific data or doing network IO operations and returning actual data that needs to be displayed on the front-end.0 @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  • 5. 5 AsyncTask with Example AsyncTask 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. The AsyncTask class encapsulates the creation of Threads and Handlers. An AsyncTask is started via the execute() method. The execute() method calls the doInBackground() and the onPostExecute() method. The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread. The onPostExecute() method synchronize itself again with the user interface thread and allows to update it. 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 the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> . TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() 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 ThreadAsynkTaskExample with an Activity called ThreadAsynkTaskActivity. Add the android.permission.INTERNET permission to 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 Following is the AsynkTask in our scenario the WebPageDownLoadTask is extending AsyncTask<String, Void, String> of android.os.AsyncTask package This 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 TextView Here is the source code for the Same If you run your application and press your button then the content of the defined webpage should be read in the background. Once this process is done your TextView will be updated. @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  • 7. 7 Session2 Broadcast Receivers The concept of Broadcast Receivers, one of the fundamental blocks of Android, is very simple. These are applications that will respond to any intent that is broadcast by other applications. Provided the broadcast intent matches the intent specified against the receiver in the AndroidManifest.xml This goes to automatically imply that many activities, events, services or the like can broadcast intents expecting the appropriate action to be automatically taken. So, to begin with, let us see the various Broadcast events that are given by the platform itself. Here is a standard list obtained from the android documentation:  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_SHUTDOWN We will define a broadcast receiver which listens to telephone state changes. If the phone receives a phone 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 in the following code @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  • 8. 8 Here is the MyBroadcastReceiver extending BroadcastReceiver class , when any Telephony call arrived and disconnected then the onReceive(Context context, Intent intent) get called . You can even register BroadcastReceiver progrmatically by using Context.registerReceiver(BroadCastReceiver bcr, IntentFilter ifilter ); To view the output of this application , install this application in your mobile Phone and make a call the BroadcastReceiver gets called @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  • 9. 9 Session 3 Understanding Services in android Role of services Service life cycle methods What is service ? A Service is an application component representing either an application's desire to perform a longer- running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.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 Background processes 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 to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() 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 didn't use in this example is bindService() which just calls the services onCreate() method but does not call the onStartCommand(). onBindService() is used to create persistance connection to the service. context.onBindService() | ->onCreate() [service created] @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  • 10. 10 Service Example This Services Demo is simple as it plays an audio file and by listening to click events of the buttons invokes the MyService service. Add any of the audio file to your res >> raw folder of an application Note : 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.xml Here is your ServicesDemo which extends Activity and implements OnClickListener @COPYRIGHTS BY Dhiraj P. karalkar karalkar.dhiraj@gmail.com
  • 11. 11 When the user clicks on the start Button then startService() method gets called which invokes your MyService’s onCreate() method , in this method we have initialize the MediaPlayer right now for this ignore 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 Player Your service is started now even if you close your activity the service will run in the Background , that is the 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 the background , this stopService() method calls the onDestroy() method of the MyService Which stops the service running in the Background Here 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