SlideShare a Scribd company logo
SCHOOL OF ENGINEERING
Activities
1
CE701
Mobile Computing
Tejas Vasavada
Android Services
Following are outcomes of this lecture:
• Students will become aware of need of using
services.
• Students will understand service life cycle.
• Students will be able to create services on
their own.
Outcomes
• A Service is an application component that
can perform long-running operations in the
background.
• It does not provide a user interface.
• Some application component can start a
service. Service will continue to run in the
background even if the user switches to
different application.
Service
• Additionally, a component can bind to a
service to interact with it and even perform
interprocess communication (IPC).
• A service can essentially take two forms:
1) Started
2) Bound
Started Service
• A service is called "started“ service if an
application component (such as an activity)
starts it by calling startService( ).
• A started service can be created in two ways:
• By extending Service class
• By extending IntentService class
Started Service
• If Service class is extended, service runs for
indefinite time. It is destroyed only if activity
destroys it using stopService( ) function.
• If IntentService class is extended, service is
immediately destroyed once its task is
completed.
• Service can destroy itself by calling stopSelf()
method.
• Usually, a started service performs a single
operation and does not return a result to the
caller.
• For example, it might download or upload a
file over the network. When the operation is
done, the service should stop itself.
Bound Service
• A service is "bound" when an application
component binds to it by calling bindService().
• A bound service offers a client-server interface
that allows components to interact with the
service, send requests and get results.
Bound Service
• A bound service runs only as long as at least
one application component is bound to it.
• Multiple components can bind to the service
at once, but when all of them unbind, the
service is destroyed.
Examples
Example 1
[started service by extending Service class]
Display two buttons on Screen : “START
METHOD” and “STOP METHOD”.
When user clicks on “START METHOD”, service
should start. When user clicks on “STOP
METHOD”, service should be stopped.
Two .java files should be present in your project:
• Service1Activity.java
• MyService1.java.
public class Service1Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startMethod(View v)
{
Intent i = new Intent(this,MyService1.class);
i.putExtra("message1","Hello to MyService1");
startService(i);
}
Service1Activity.java
public void stopMethod(View v)
{
Intent i = new Intent(this,MyService1.class);
stopService(i);
}
}
public class MyService1 extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "Service Created",10).show();
super.onCreate();
}
MyService1.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
String msg = intent.getStringExtra("message1");
Toast.makeText(this, "Service Started" + msg,10).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(this, "Service Destroyed",10).show();
super.onDestroy(); }
} // end of class MyService1
• Service is started using startService(i) call.
Intent i contains name of service class.
• When service is created, onCreate() method is
called by system.
• Then onStartCommand() is called by system.
• Service is not destroyed automatically.
• stopService(i) destroys the service.
• When service is destroyed, onDestroy()
method is called by system.
• Thus life cycle of Started service contains
three callback methods: onCreate,
onStartCommand() and onDestroy().
Example 2
[started service by extending IntentService
class].
• GUI is same as Example 1.
• Implement service in demoIntentService.java.
• Use same activity file. Make appropriate
changes in Activity file.
public class demoIntentService extends IntentService{
public demoIntentService() {
super("Intent Service");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String msg = intent.getStringExtra("message1");
Toast.makeText(this, "onHandleIntent called" + msg,
Toast.LENGTH_LONG).show();
Log.d("handleIntent","it is called");
}
demoIntentService.java
@Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "onCreate called", Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "onStartCommand called",
Toast.LENGTH_LONG).show();
onHandleIntent(intent);
super.onStartCommand(intent, flags, startId);
return 1;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(this, "onDestroy called", Toast.LENGTH_LONG).show();
super.onDestroy();
}
}
• When service starts, onCreate() is called. Then
onStartCommand().
• From onStartCommand(), onHandleIntent() is
explicitly called.
• Service is destroyed on its own once
onHandleIntent() is completed.
Example 3
[Bound service by extending Service class].
GUI has three buttons, “BIND SERVICE”,
“UNBIND SERVICE”, “FIND FACTORIAL”.
One EditText control is present. User enters a
number in it. Then clicks on “FIND
FACTORIAL”. Service finds factorial of given
number.
public class Service2Activity extends Activity {
/** Called when the activity is first created. */
MyService mservice;
boolean status;
EditText number;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
number = (EditText)findViewById(R.id.editText1);
}
Service2Activity.java
public void bindMethod(View v){
Intent intent = new Intent(this, MyService.class);
bindService(intent, sc, Context.BIND_AUTO_CREATE);
Toast.makeText(Service2Activity.this, "bindMethod called",
Toast.LENGTH_LONG).show();
}
public void unbindMethod(View v){
unbindService(sc);
status = false;
Toast.makeText(Service2Activity.this, "unbindMethod called",
Toast.LENGTH_LONG).show();
}
public void factorialMethod(View v)
{
if(status)
{
int num,fact;
num = Integer.parseInt(number.getText().toString());
fact = mservice.findFactorial(num);
Toast.makeText(this,"Factorial is " +
fact,Toast.LENGTH_LONG).show();
}
}
private ServiceConnection sc = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
Toast.makeText(Service2Activity.this, "onServiceConnected started",
Toast.LENGTH_LONG).show();
LocalBinder binder = (LocalBinder)arg1;
mservice = binder.getService();
status = true;
Toast.makeText(Service2Activity.this, "onServiceConnected completed",
Toast.LENGTH_LONG).show();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
status = false;
Toast.makeText(Service2Activity.this, "onServiceDisConnected called",
Toast.LENGTH_LONG).show();
}
}; // end of ServiceConnection class
} // end of Activity class
public class MyService extends Service {
public final IBinder mbinder = new LocalBinder();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "IBinder called", Toast.LENGTH_LONG).show();
return mbinder;
}
public class LocalBinder extends Binder{
public MyService getService(){
Toast.makeText(MyService.this, "LocalBinder.getService() called",
Toast.LENGTH_LONG).show();
return MyService.this;}
}
MyService.java
public int findFactorial(int x){
int fact = 1;
for(int i=1;i<=x;i++)
{
fact = fact * I;
}
return fact;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this,"Service created", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this,"Service Destroyed", Toast.LENGTH_LONG).show();
}
}
• When user clicks on “BIND SERVICE”,
bindMethod() is called.
• In bindMethod(), bindService() is invoked. It is
an in-built method.
• bindServie() contains following arguments:
intent, service connection and flag.
• As next step, service is created if it is not
running.
• When service is created, onCreate( ) is called.
Then onBind() is called.
• Object returned by onBind() is stored in ‘arg1’
in onServiceConnected() method of
ServiceConnection class.
• ‘arg1’ is assigned to ‘binder’ object in the
same method.
• Then getService() method is called. Its return
value is assigned to mservice object.
• mservice is object of MyService class.
• When user clicks on “FindFactorial”,
findFactorial() method of MyService.java is
called.
• Bound service created by above example is
local to application.
• Second way of creating bound service is to use
Messenger class.
• If Messenger class is used, service can be used
by a component outside the application
hosting the service.
• Find answer of following question yourself :
When onServiceDisconnected() is called ?
Example 4
[bound service by using Messenger class].
Activity sends a message to service. Service
receives the message and displays it.
Refer to service3.tar uploaded in edmodo for
detailed code.
• Following files are uploaded in edmodo:
• Service1.tar – for started service
• Service2.tar – for bound service (example 3)
• Service3.tar – for example 4
• We have discussed about started and bound
services.
• Each of them can be created in two different
ways.
• Services are different than Activities. They
don’t have GUI.
Summary
• Website: developer.android.com
• Chapter 21, Working with Services from
Android Wireless Application Development
by Darcy and Conder
• Videos shared on FTP
Readings

More Related Content

What's hot

Introduction to android
Introduction to androidIntroduction to android
Introduction to android
Arbuleac Eugeniu
 
Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification Google
Mathias Seguy
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
Mike Nakhimovich
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and thread
MengChun Lam
 
Android Testing
Android TestingAndroid Testing
Android Testing
Evan Lin
 
MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2
PROIDEA
 
Dynamic Elements
Dynamic ElementsDynamic Elements
Dynamic Elements
WO Community
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
Lilia Sfaxi
 
DotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdfDotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdf
arunagulla
 
読むと怖くないDagger2
読むと怖くないDagger2読むと怖くないDagger2
読むと怖くないDagger2
shinnosuke kugimiya
 
Exercises
ExercisesExercises
Exercises
maamir farooq
 
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
John Ferguson Smart Limited
 
Asynchronous Programming in Android
Asynchronous Programming in AndroidAsynchronous Programming in Android
Asynchronous Programming in Android
John Pendexter
 
Introj Query Pt2
Introj Query Pt2Introj Query Pt2
Introj Query Pt2
kshyju
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
DataArt
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32
Bilal Ahmed
 
Intro to Dependency Injection - Or bar
Intro to Dependency Injection - Or bar Intro to Dependency Injection - Or bar
Intro to Dependency Injection - Or bar
DroidConTLV
 
Bot builder v4 HOL
Bot builder v4 HOLBot builder v4 HOL
Bot builder v4 HOL
Cheah Eng Soon
 
Swing
SwingSwing

What's hot (19)

Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification Google
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and thread
 
Android Testing
Android TestingAndroid Testing
Android Testing
 
MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2
 
Dynamic Elements
Dynamic ElementsDynamic Elements
Dynamic Elements
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
DotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdfDotNetNuke Client API -DragDropAdminModules.pdf
DotNetNuke Client API -DragDropAdminModules.pdf
 
読むと怖くないDagger2
読むと怖くないDagger2読むと怖くないDagger2
読むと怖くないDagger2
 
Exercises
ExercisesExercises
Exercises
 
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
 
Asynchronous Programming in Android
Asynchronous Programming in AndroidAsynchronous Programming in Android
Asynchronous Programming in Android
 
Introj Query Pt2
Introj Query Pt2Introj Query Pt2
Introj Query Pt2
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32
 
Intro to Dependency Injection - Or bar
Intro to Dependency Injection - Or bar Intro to Dependency Injection - Or bar
Intro to Dependency Injection - Or bar
 
Bot builder v4 HOL
Bot builder v4 HOLBot builder v4 HOL
Bot builder v4 HOL
 
Swing
SwingSwing
Swing
 

Viewers also liked

Poriferos
PoriferosPoriferos
Origen de la vida
Origen de la vidaOrigen de la vida
Origen de la vida
Emperatriz Herrera
 
VET FEE-HELP
VET FEE-HELPVET FEE-HELP
VET FEE-HELP
Olivia Coleman
 
Door knocking guidelines
Door knocking guidelinesDoor knocking guidelines
Door knocking guidelines
Olivia Coleman
 
VET FEE-HELP Presentation
VET FEE-HELP PresentationVET FEE-HELP Presentation
VET FEE-HELP Presentation
Olivia Coleman
 
Enrolment Process
Enrolment ProcessEnrolment Process
Enrolment Process
Olivia Coleman
 
Artrópodos
ArtrópodosArtrópodos
Artrópodos
Emperatriz Herrera
 
Power Point Presentation
Power Point PresentationPower Point Presentation
Power Point Presentation
Jacqueline Kehr
 
Poriferos
Poriferos Poriferos
Poriferos
Emperatriz Herrera
 
Үг бүтэх арга
Үг бүтэх аргаҮг бүтэх арга
Үг бүтэх арга
М. Цэнд-Аюуш
 
Эх, түүний үндсэн шинж
Эх, түүний үндсэн шинжЭх, түүний үндсэн шинж
Эх, түүний үндсэн шинж
М. Цэнд-Аюуш
 
“Мөнгө” цахим хичээл
“Мөнгө” цахим хичээл“Мөнгө” цахим хичээл
“Мөнгө” цахим хичээл
М. Цэнд-Аюуш
 
Minesweeper專題報告
Minesweeper專題報告Minesweeper專題報告
Minesweeper專題報告
?? ?
 
эхэд задлал хийх нь
эхэд задлал хийх ньэхэд задлал хийх нь
эхэд задлал хийх нь
М. Цэнд-Аюуш
 

Viewers also liked (14)

Poriferos
PoriferosPoriferos
Poriferos
 
Origen de la vida
Origen de la vidaOrigen de la vida
Origen de la vida
 
VET FEE-HELP
VET FEE-HELPVET FEE-HELP
VET FEE-HELP
 
Door knocking guidelines
Door knocking guidelinesDoor knocking guidelines
Door knocking guidelines
 
VET FEE-HELP Presentation
VET FEE-HELP PresentationVET FEE-HELP Presentation
VET FEE-HELP Presentation
 
Enrolment Process
Enrolment ProcessEnrolment Process
Enrolment Process
 
Artrópodos
ArtrópodosArtrópodos
Artrópodos
 
Power Point Presentation
Power Point PresentationPower Point Presentation
Power Point Presentation
 
Poriferos
Poriferos Poriferos
Poriferos
 
Үг бүтэх арга
Үг бүтэх аргаҮг бүтэх арга
Үг бүтэх арга
 
Эх, түүний үндсэн шинж
Эх, түүний үндсэн шинжЭх, түүний үндсэн шинж
Эх, түүний үндсэн шинж
 
“Мөнгө” цахим хичээл
“Мөнгө” цахим хичээл“Мөнгө” цахим хичээл
“Мөнгө” цахим хичээл
 
Minesweeper專題報告
Minesweeper專題報告Minesweeper專題報告
Minesweeper專題報告
 
эхэд задлал хийх нь
эхэд задлал хийх ньэхэд задлал хийх нь
эхэд задлал хийх нь
 

Similar to 9 services

Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
Utkarsh Mankad
 
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
Lifeparticle
 
Android101
Android101Android101
Android101
David Marques
 
Architecture your android_application
Architecture your android_applicationArchitecture your android_application
Architecture your android_application
Mark Brady
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
PSTechSerbia
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
Shanmugapriya D
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
Khaled Anaqwa
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
Ahsanul Karim
 
Services I.pptx
Services I.pptxServices I.pptx
Services I.pptx
RiziX3
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
Jussi Pohjolainen
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
Lars Vogel
 
02 hello world - Android
02   hello world - Android02   hello world - Android
02 hello world - Android
Wingston
 
Android classes in mumbai
Android classes in mumbaiAndroid classes in mumbai
Android classes in mumbai
Vibrant Technologies & Computers
 
04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)
TECOS
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdf
ssusere71a07
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
Alexis Hassler
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
Utkarsh Mankad
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
Michael Bakogiannis
 
Level 1 &amp; 2
Level 1 &amp; 2Level 1 &amp; 2
Level 1 &amp; 2
skumartarget
 
Unity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 pluginUnity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 plugin
David Douglas
 

Similar to 9 services (20)

Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
 
Android101
Android101Android101
Android101
 
Architecture your android_application
Architecture your android_applicationArchitecture your android_application
Architecture your android_application
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
 
Services I.pptx
Services I.pptxServices I.pptx
Services I.pptx
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 
02 hello world - Android
02   hello world - Android02   hello world - Android
02 hello world - Android
 
Android classes in mumbai
Android classes in mumbaiAndroid classes in mumbai
Android classes in mumbai
 
04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdf
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Level 1 &amp; 2
Level 1 &amp; 2Level 1 &amp; 2
Level 1 &amp; 2
 
Unity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 pluginUnity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 plugin
 

9 services

  • 1. SCHOOL OF ENGINEERING Activities 1 CE701 Mobile Computing Tejas Vasavada Android Services
  • 2. Following are outcomes of this lecture: • Students will become aware of need of using services. • Students will understand service life cycle. • Students will be able to create services on their own. Outcomes
  • 3. • A Service is an application component that can perform long-running operations in the background. • It does not provide a user interface. • Some application component can start a service. Service will continue to run in the background even if the user switches to different application. Service
  • 4. • Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). • A service can essentially take two forms: 1) Started 2) Bound
  • 6. • A service is called "started“ service if an application component (such as an activity) starts it by calling startService( ). • A started service can be created in two ways: • By extending Service class • By extending IntentService class Started Service
  • 7. • If Service class is extended, service runs for indefinite time. It is destroyed only if activity destroys it using stopService( ) function. • If IntentService class is extended, service is immediately destroyed once its task is completed. • Service can destroy itself by calling stopSelf() method.
  • 8. • Usually, a started service performs a single operation and does not return a result to the caller. • For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
  • 10. • A service is "bound" when an application component binds to it by calling bindService(). • A bound service offers a client-server interface that allows components to interact with the service, send requests and get results. Bound Service
  • 11. • A bound service runs only as long as at least one application component is bound to it. • Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
  • 13. Example 1 [started service by extending Service class] Display two buttons on Screen : “START METHOD” and “STOP METHOD”. When user clicks on “START METHOD”, service should start. When user clicks on “STOP METHOD”, service should be stopped.
  • 14. Two .java files should be present in your project: • Service1Activity.java • MyService1.java.
  • 15. public class Service1Activity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startMethod(View v) { Intent i = new Intent(this,MyService1.class); i.putExtra("message1","Hello to MyService1"); startService(i); } Service1Activity.java
  • 16. public void stopMethod(View v) { Intent i = new Intent(this,MyService1.class); stopService(i); } }
  • 17. public class MyService1 extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub Toast.makeText(this, "Service Created",10).show(); super.onCreate(); } MyService1.java
  • 18. @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub String msg = intent.getStringExtra("message1"); Toast.makeText(this, "Service Started" + msg,10).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { // TODO Auto-generated method stub Toast.makeText(this, "Service Destroyed",10).show(); super.onDestroy(); } } // end of class MyService1
  • 19. • Service is started using startService(i) call. Intent i contains name of service class. • When service is created, onCreate() method is called by system. • Then onStartCommand() is called by system. • Service is not destroyed automatically. • stopService(i) destroys the service.
  • 20. • When service is destroyed, onDestroy() method is called by system. • Thus life cycle of Started service contains three callback methods: onCreate, onStartCommand() and onDestroy().
  • 21. Example 2 [started service by extending IntentService class]. • GUI is same as Example 1. • Implement service in demoIntentService.java. • Use same activity file. Make appropriate changes in Activity file.
  • 22. public class demoIntentService extends IntentService{ public demoIntentService() { super("Intent Service"); // TODO Auto-generated constructor stub } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub String msg = intent.getStringExtra("message1"); Toast.makeText(this, "onHandleIntent called" + msg, Toast.LENGTH_LONG).show(); Log.d("handleIntent","it is called"); } demoIntentService.java
  • 23. @Override public void onCreate() { // TODO Auto-generated method stub Toast.makeText(this, "onCreate called", Toast.LENGTH_LONG).show(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub Toast.makeText(this, "onStartCommand called", Toast.LENGTH_LONG).show(); onHandleIntent(intent); super.onStartCommand(intent, flags, startId);
  • 24. return 1; } @Override public void onDestroy() { // TODO Auto-generated method stub Toast.makeText(this, "onDestroy called", Toast.LENGTH_LONG).show(); super.onDestroy(); } }
  • 25. • When service starts, onCreate() is called. Then onStartCommand(). • From onStartCommand(), onHandleIntent() is explicitly called. • Service is destroyed on its own once onHandleIntent() is completed.
  • 26. Example 3 [Bound service by extending Service class]. GUI has three buttons, “BIND SERVICE”, “UNBIND SERVICE”, “FIND FACTORIAL”. One EditText control is present. User enters a number in it. Then clicks on “FIND FACTORIAL”. Service finds factorial of given number.
  • 27. public class Service2Activity extends Activity { /** Called when the activity is first created. */ MyService mservice; boolean status; EditText number; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); number = (EditText)findViewById(R.id.editText1); } Service2Activity.java
  • 28. public void bindMethod(View v){ Intent intent = new Intent(this, MyService.class); bindService(intent, sc, Context.BIND_AUTO_CREATE); Toast.makeText(Service2Activity.this, "bindMethod called", Toast.LENGTH_LONG).show(); } public void unbindMethod(View v){ unbindService(sc); status = false; Toast.makeText(Service2Activity.this, "unbindMethod called", Toast.LENGTH_LONG).show(); }
  • 29. public void factorialMethod(View v) { if(status) { int num,fact; num = Integer.parseInt(number.getText().toString()); fact = mservice.findFactorial(num); Toast.makeText(this,"Factorial is " + fact,Toast.LENGTH_LONG).show(); } }
  • 30. private ServiceConnection sc = new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { // TODO Auto-generated method stub Toast.makeText(Service2Activity.this, "onServiceConnected started", Toast.LENGTH_LONG).show(); LocalBinder binder = (LocalBinder)arg1; mservice = binder.getService(); status = true; Toast.makeText(Service2Activity.this, "onServiceConnected completed", Toast.LENGTH_LONG).show(); }
  • 31. @Override public void onServiceDisconnected(ComponentName arg0) { // TODO Auto-generated method stub status = false; Toast.makeText(Service2Activity.this, "onServiceDisConnected called", Toast.LENGTH_LONG).show(); } }; // end of ServiceConnection class } // end of Activity class
  • 32. public class MyService extends Service { public final IBinder mbinder = new LocalBinder(); @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub Toast.makeText(this, "IBinder called", Toast.LENGTH_LONG).show(); return mbinder; } public class LocalBinder extends Binder{ public MyService getService(){ Toast.makeText(MyService.this, "LocalBinder.getService() called", Toast.LENGTH_LONG).show(); return MyService.this;} } MyService.java
  • 33. public int findFactorial(int x){ int fact = 1; for(int i=1;i<=x;i++) { fact = fact * I; } return fact; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Toast.makeText(this,"Service created", Toast.LENGTH_LONG).show(); }
  • 34. @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Toast.makeText(this,"Service Destroyed", Toast.LENGTH_LONG).show(); } }
  • 35. • When user clicks on “BIND SERVICE”, bindMethod() is called. • In bindMethod(), bindService() is invoked. It is an in-built method. • bindServie() contains following arguments: intent, service connection and flag.
  • 36. • As next step, service is created if it is not running. • When service is created, onCreate( ) is called. Then onBind() is called. • Object returned by onBind() is stored in ‘arg1’ in onServiceConnected() method of ServiceConnection class.
  • 37. • ‘arg1’ is assigned to ‘binder’ object in the same method. • Then getService() method is called. Its return value is assigned to mservice object. • mservice is object of MyService class. • When user clicks on “FindFactorial”, findFactorial() method of MyService.java is called.
  • 38. • Bound service created by above example is local to application. • Second way of creating bound service is to use Messenger class. • If Messenger class is used, service can be used by a component outside the application hosting the service.
  • 39. • Find answer of following question yourself : When onServiceDisconnected() is called ?
  • 40. Example 4 [bound service by using Messenger class]. Activity sends a message to service. Service receives the message and displays it. Refer to service3.tar uploaded in edmodo for detailed code.
  • 41. • Following files are uploaded in edmodo: • Service1.tar – for started service • Service2.tar – for bound service (example 3) • Service3.tar – for example 4
  • 42. • We have discussed about started and bound services. • Each of them can be created in two different ways. • Services are different than Activities. They don’t have GUI. Summary
  • 43. • Website: developer.android.com • Chapter 21, Working with Services from Android Wireless Application Development by Darcy and Conder • Videos shared on FTP Readings