SlideShare a Scribd company logo
Android Background Processing – Services
and IPC
Android Services
A Service is an application component that can perform long-running operations in the background and does not
provide a user interface.
A service can essentially take two forms:
Started : A service is "started" when an application component (such as an activity) starts it by calling startService().
Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
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
Bound : 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, get results, and
even do so across processes with interprocess communication (IPC). A bound service runs only as long as another
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.
Android Services – The Basics
To create a service, you must create a subclass of Service (or one of its existing subclasses). In your implementation, you
need to override some callback methods
The most important callback methods you should override are:
onStartCommand() : The system calls this method when another component, such as an activity, requests that the
service be started, by calling startService(). Once this method executes, the service is started and can run in the
background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done,
onBind() : The system calls this method when another component wants to bind with the service (such as to perform
RPC), by calling bindService(). In your implementation of this method, you must provide an interface that clients use to
communicate with the service, by returning an IBinder.
onCreate() : The system calls this method when the service is first created, to perform one-time setup procedures
(before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.
onDestroy() : The system calls this method when the service is no longer used and is being destroyed. Your service
should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call
the service receives.
Service Life Cycle
Started Service
A started service is one that another component starts by calling startService(), resulting in a call to the service's
onStartCommand() method.
When a service is started, it has a lifecycle that's independent of the component that started it and the service can run in
the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself
when its job is done by calling stopSelf(), or another component can stop it by calling stopService().
Traditionally, there are two classes you can extend to create a started service:
Service : This is the base class for all services. When you extend this class, it's important that you create a new thread in
which to do all the service's work, because the service uses your application's main thread, by default, which could slow
the performance of any activity your application is running.
IntentService : This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the
best option if you don't require that your service handle multiple requests simultaneously. All you need to do is
implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
Most started services don't need to handle multiple requests simultaneously (which can actually be a dangerous
multi-threading scenario), it's probably best if you implement your service using the IntentService class.
The IntentService does the following:
1. Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your
application's main thread.
2. Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never
have to worry about multi-threading.
3. Stops the service after all start requests have been handled, so you never have to call stopSelf().
4. Provides default implementation of onBind() that returns null.
5. Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to
your onHandleIntent() implementation.
Intent Services
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
Structure of an IntentService
Service Operations
Start a Service
You can start a service from an activity or other application component by passing an Intent (specifying the service to
start) to startService(). The Android system calls the service's onStartCommand() method and passes it the Intent.
Intent intent = new Intent(this, HelloService.class);
startService(intent);
Stop a Service
A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it
must recover system memory and the service continues to run after onStartCommand() returns. So, the service
must stop itself by calling stopSelf() or another component can stop it by calling stopService().
Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.
Running a Service in Foreground
A foreground service is a service that's considered to be something the user is actively aware of and thus not a
candidate for the system to kill when low on memory. A foreground service must provide a notification for the status
bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the
service is either stopped or removed from the foreground.
To request that your service run in the foreground, call startForeground(). This method takes two parameters: an integer
that uniquely identifies the notification and the Notification for the status bar. For example:
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
Bound Services
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.
To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder
object that defines the programming interface that clients can use to interact with the service.
A client can bind to the service by calling bindService(). When it does, it must provide an implementation of
ServiceConnection, which monitors the connection with the service. The bindService() method returns immediately
without a value, but when the Android system creates the connection between the client and service, it calls
onServiceConnected() on the ServiceConnection, to deliver the IBinder that the client can use to communicate with the
service.
Creating a Bind Service
When creating a service that provides binding, you must provide an IBinder that provides the programming interface
that clients can use to interact with the service. There are three ways you can define the interface:
Extending the Binder class : If your service is private to your own application and runs in the same process as the
client (which is common), you should create your interface by extending the Binder class and returning an instance of
it from onBind().
Using a Messenger : If you need your interface to work across different processes, you can create an interface for the
service with a Messenger. In this manner, the service defines a Handler that responds to different types of Message
objects.
Using AIDL : AIDL (Android Interface Definition Language) performs all the work to decompose objects into primitives
that the operating system can understand and marshall them across processes to perform IPC. The previous
technique, using a Messenger, is actually based on AIDL as its underlying structure.
Extending Binder Class
If your service is used only by the local application and does not need to work across processes, then you can
implement your own Binder class that provides your client direct access to public methods in the service.
Here's how to set it up:
1. In your service, create an instance of Binder that either:
1. contains public methods that the client can call
2. returns the current Service instance, which has public methods the client can call
3. or, returns an instance of another class hosted by the service with public methods the client can call
2. Return this instance of Binder from the onBind() callback method.
3. In the client, receive the Binder from the onServiceConnected() callback method and make calls to the bound
service using the methods provided.
Using a Messenger
If you need your service to communicate with remote processes, then you can use a Messenger to provide the
interface for your service. This technique allows you to perform interprocess communication (IPC) without the need to
use AIDL.
Here's a summary of how to use a Messenger:
1. The service implements a Handler that receives a callback for each call from a client.
2. The Handler is used to create a Messenger object (which is a reference to the Handler).
3. The Messenger creates an IBinder that the service returns to clients from onBind().
4. Clients use the IBinder to instantiate the Messenger (that references the service's Handler), which the client uses
to send Message objects to the service.
5. The service receives each Message in its Handler—specifically, in the handleMessage() method.
AIDL – Android Interface Definition Language
AIDL (Android Interface Definition Language) allows you to define the programming interface that both the
client and service agree upon in order to communicate with each other using interprocess communication
(IPC).
On Android, one process cannot normally access the memory of another process. So to talk, they need to
decompose their objects into primitives that the operating system can understand, and marshall the objects
across that boundary for you.
Steps in implementing AIDL in your program
You must define your AIDL interface in an .aidl file using the Java programming language syntax, then save it
in the source code (in the src/ directory) of both the application hosting the service and any other
application that binds to the service.
When you build each application that contains the .aidl file, the Android SDK tools generate an IBinder
interface based on the .aidl file and save it in the project's gen/ directory. The service must implement the
IBinder interface as appropriate. The client applications can then bind to the service and call methods from
the IBinder to perform IPC.
To create a bounded service using AIDL, follow these steps:
1. Create the .aidl file : This file defines the programming interface with method signatures.
2. Implement the interface : The Android SDK tools generate an interface in the Java programming
language, based on your .aidl file. This interface has an inner abstract class named Stub that extends
Binder and implements methods from your AIDL interface. You must extend the Stub class and
implement the methods.
3. Expose the interface to clients : Implement a Service and override onBind() to return your
implementation of the Stub class.
1. Creating a .aidl file
// IRemoteService.aidl
package com.example.android;
// Declare any non-default types here with import statements
/** Example service interface */
interface IRemoteService {
/** Request the process ID of this service, to do evil things with it. */
int getPid();
/** Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
Create a file with .aidl extention into the project/src folder. Write the file in above shown manner.
2. Implementing the interface in Service class
When you build your application, the Android SDK tools generate a .java interface file named after your .aidl
file. The generated interface includes a subclass named Stub that is an abstract implementation of its parent
interface (for example, YourInterface.Stub) and declares all the methods from the .aidl file.
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid(){
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
3. Exposing your interface to your clients
Once you've implemented the interface for your service, you need to expose it to clients so they can bind to it.
To expose the interface for your service, extend Service and implement onBind() to return an instance of your
class that implements the generated Stub (as discussed in the previous section). Here's an example service that
exposes the IRemoteService example interface to clients.
public class RemoteService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// Return the interface
return mBinder;
}
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid(){
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
}
Ad

More Related Content

What's hot (20)

Android AIDL Concept
Android AIDL ConceptAndroid AIDL Concept
Android AIDL Concept
Charile Tsai
 
Low Level View of Android System Architecture
Low Level View of Android System ArchitectureLow Level View of Android System Architecture
Low Level View of Android System Architecture
National Cheng Kung University
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
National Cheng Kung University
 
Embedded Android : System Development - Part III
Embedded Android : System Development - Part IIIEmbedded Android : System Development - Part III
Embedded Android : System Development - Part III
Emertxe Information Technologies Pvt Ltd
 
Android Boot Time Optimization
Android Boot Time OptimizationAndroid Boot Time Optimization
Android Boot Time Optimization
Kan-Ru Chen
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Opersys inc.
 
Learning AOSP - Android Booting Process
Learning AOSP - Android Booting ProcessLearning AOSP - Android Booting Process
Learning AOSP - Android Booting Process
Nanik Tolaram
 
Android Binder IPC for Linux
Android Binder IPC for LinuxAndroid Binder IPC for Linux
Android Binder IPC for Linux
Yu-Hsin Hung
 
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
Nanik Tolaram
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in Android
Malwinder Singh
 
Embedded Android Workshop
Embedded Android WorkshopEmbedded Android Workshop
Embedded Android Workshop
Opersys inc.
 
Android 10
Android 10Android 10
Android 10
kpraveen_slideshare
 
Init of Android
Init of AndroidInit of Android
Init of Android
Tetsuyuki Kobayashi
 
Android Treble: Blessing or Trouble?
Android Treble: Blessing or Trouble?Android Treble: Blessing or Trouble?
Android Treble: Blessing or Trouble?
Opersys inc.
 
Embedded Android : System Development - Part I
Embedded Android : System Development - Part IEmbedded Android : System Development - Part I
Embedded Android : System Development - Part I
Emertxe Information Technologies Pvt Ltd
 
Android Storage - Vold
Android Storage - VoldAndroid Storage - Vold
Android Storage - Vold
William Lee
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaAndroid | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
JAX London
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
Emertxe Information Technologies Pvt Ltd
 
Android Service Intro
Android Service IntroAndroid Service Intro
Android Service Intro
Jintin Lin
 
Android device driver structure introduction
Android device driver structure introductionAndroid device driver structure introduction
Android device driver structure introduction
William Liang
 
Android AIDL Concept
Android AIDL ConceptAndroid AIDL Concept
Android AIDL Concept
Charile Tsai
 
Android Boot Time Optimization
Android Boot Time OptimizationAndroid Boot Time Optimization
Android Boot Time Optimization
Kan-Ru Chen
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Opersys inc.
 
Learning AOSP - Android Booting Process
Learning AOSP - Android Booting ProcessLearning AOSP - Android Booting Process
Learning AOSP - Android Booting Process
Nanik Tolaram
 
Android Binder IPC for Linux
Android Binder IPC for LinuxAndroid Binder IPC for Linux
Android Binder IPC for Linux
Yu-Hsin Hung
 
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
Nanik Tolaram
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in Android
Malwinder Singh
 
Embedded Android Workshop
Embedded Android WorkshopEmbedded Android Workshop
Embedded Android Workshop
Opersys inc.
 
Android Treble: Blessing or Trouble?
Android Treble: Blessing or Trouble?Android Treble: Blessing or Trouble?
Android Treble: Blessing or Trouble?
Opersys inc.
 
Android Storage - Vold
Android Storage - VoldAndroid Storage - Vold
Android Storage - Vold
William Lee
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaAndroid | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
JAX London
 
Android Service Intro
Android Service IntroAndroid Service Intro
Android Service Intro
Jintin Lin
 
Android device driver structure introduction
Android device driver structure introductionAndroid device driver structure introduction
Android device driver structure introduction
William Liang
 

Viewers also liked (19)

Android service
Android serviceAndroid service
Android service
Kirill Rozov
 
Android Hacks - 合宿 Service
Android Hacks - 合宿 ServiceAndroid Hacks - 合宿 Service
Android Hacks - 合宿 Service
Masanori Ohkawara
 
AIDL - Android Interface Definition Language
AIDL  - Android Interface Definition LanguageAIDL  - Android Interface Definition Language
AIDL - Android Interface Definition Language
Arvind Devaraj
 
IPC: AIDL is not a curse
IPC: AIDL is not a curseIPC: AIDL is not a curse
IPC: AIDL is not a curse
Yonatan Levin
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
Diego Grancini
 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
Perfect APK
 
Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014
Paris Android User Group
 
Thread management
Thread management Thread management
Thread management
Ayaan Adeel
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]
Nehil Jain
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
Jussi Pohjolainen
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
Ahsanul Karim
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
Utkarsh Mankad
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
Android intents
Android intentsAndroid intents
Android intents
Siva Ramakrishna kv
 
Binary tree
Binary  treeBinary  tree
Binary tree
Vanitha Chandru
 
Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
Anders Göransson
 
Android - Intents - Mazenet Solution
Android - Intents - Mazenet SolutionAndroid - Intents - Mazenet Solution
Android - Intents - Mazenet Solution
Mazenetsolution
 
Creating apps that work on all screen sizes
Creating apps that work on all screen sizesCreating apps that work on all screen sizes
Creating apps that work on all screen sizes
Ravi Vyas
 
Android Hacks - 合宿 Service
Android Hacks - 合宿 ServiceAndroid Hacks - 合宿 Service
Android Hacks - 合宿 Service
Masanori Ohkawara
 
AIDL - Android Interface Definition Language
AIDL  - Android Interface Definition LanguageAIDL  - Android Interface Definition Language
AIDL - Android Interface Definition Language
Arvind Devaraj
 
IPC: AIDL is not a curse
IPC: AIDL is not a curseIPC: AIDL is not a curse
IPC: AIDL is not a curse
Yonatan Levin
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
Diego Grancini
 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
Perfect APK
 
Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014
Paris Android User Group
 
Thread management
Thread management Thread management
Thread management
Ayaan Adeel
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]
Nehil Jain
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
Utkarsh Mankad
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
Android - Intents - Mazenet Solution
Android - Intents - Mazenet SolutionAndroid - Intents - Mazenet Solution
Android - Intents - Mazenet Solution
Mazenetsolution
 
Creating apps that work on all screen sizes
Creating apps that work on all screen sizesCreating apps that work on all screen sizes
Creating apps that work on all screen sizes
Ravi Vyas
 
Ad

Similar to Android service, aidl - day 1 (20)

Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
Khaled Anaqwa
 
Services I.pptx
Services I.pptxServices I.pptx
Services I.pptx
RiziX3
 
Android service and gcm
Android service and gcmAndroid service and gcm
Android service and gcm
Ran Zeller
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 Services
Diego Grancini
 
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLEINTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
Kalpana Mohan
 
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLEINTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
Kalpana Mohan
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
Ahsanul Karim
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changes
InnovationM
 
Android service
Android serviceAndroid service
Android service
Krazy Koder
 
02. Android application development_Lec2.pptx
02. Android application development_Lec2.pptx02. Android application development_Lec2.pptx
02. Android application development_Lec2.pptx
anychowdhury2
 
Architecture your android_application
Architecture your android_applicationArchitecture your android_application
Architecture your android_application
Mark Brady
 
Android101
Android101Android101
Android101
David Marques
 
Android Services
Android ServicesAndroid Services
Android Services
Ahsanul Karim
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
Shanmugapriya D
 
Delphi - Howto Services
Delphi - Howto ServicesDelphi - Howto Services
Delphi - Howto Services
Niall Munro
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
Matteo Bonifazi
 
9 services
9 services9 services
9 services
Ajayvorar
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
Somenath Mukhopadhyay
 
Andriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptxAndriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptx
faiz324545
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
Khaled Anaqwa
 
Services I.pptx
Services I.pptxServices I.pptx
Services I.pptx
RiziX3
 
Android service and gcm
Android service and gcmAndroid service and gcm
Android service and gcm
Ran Zeller
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 Services
Diego Grancini
 
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLEINTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
Kalpana Mohan
 
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLEINTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
Kalpana Mohan
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
Ahsanul Karim
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changes
InnovationM
 
02. Android application development_Lec2.pptx
02. Android application development_Lec2.pptx02. Android application development_Lec2.pptx
02. Android application development_Lec2.pptx
anychowdhury2
 
Architecture your android_application
Architecture your android_applicationArchitecture your android_application
Architecture your android_application
Mark Brady
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
Shanmugapriya D
 
Delphi - Howto Services
Delphi - Howto ServicesDelphi - Howto Services
Delphi - Howto Services
Niall Munro
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
Matteo Bonifazi
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
Somenath Mukhopadhyay
 
Andriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptxAndriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptx
faiz324545
 
Ad

Recently uploaded (20)

2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 

Android service, aidl - day 1

  • 1. Android Background Processing – Services and IPC
  • 2. Android Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. A service can essentially take two forms: Started : A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. 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 Bound : 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, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another 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.
  • 3. Android Services – The Basics To create a service, you must create a subclass of Service (or one of its existing subclasses). In your implementation, you need to override some callback methods The most important callback methods you should override are: onStartCommand() : The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, onBind() : The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. onCreate() : The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called. onDestroy() : The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.
  • 5. Started Service A started service is one that another component starts by calling startService(), resulting in a call to the service's onStartCommand() method. When a service is started, it has a lifecycle that's independent of the component that started it and the service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is done by calling stopSelf(), or another component can stop it by calling stopService(). Traditionally, there are two classes you can extend to create a started service: Service : This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running. IntentService : This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
  • 6. Most started services don't need to handle multiple requests simultaneously (which can actually be a dangerous multi-threading scenario), it's probably best if you implement your service using the IntentService class. The IntentService does the following: 1. Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread. 2. Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading. 3. Stops the service after all start requests have been handled, so you never have to call stopSelf(). 4. Provides default implementation of onBind() that returns null. 5. Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation. Intent Services
  • 7. public class HelloIntentService extends IntentService { /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ public HelloIntentService() { super("HelloIntentService"); } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ @Override protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. long endTime = System.currentTimeMillis() + 5*1000; while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } } } Structure of an IntentService
  • 8. Service Operations Start a Service You can start a service from an activity or other application component by passing an Intent (specifying the service to start) to startService(). The Android system calls the service's onStartCommand() method and passes it the Intent. Intent intent = new Intent(this, HelloService.class); startService(intent); Stop a Service A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. So, the service must stop itself by calling stopSelf() or another component can stop it by calling stopService(). Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.
  • 9. Running a Service in Foreground A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground. To request that your service run in the foreground, call startForeground(). This method takes two parameters: an integer that uniquely identifies the notification and the Notification for the status bar. For example: Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis()); Intent notificationIntent = new Intent(this, ExampleActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); startForeground(ONGOING_NOTIFICATION, notification);
  • 10. Bound Services 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. To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming interface that clients can use to interact with the service. A client can bind to the service by calling bindService(). When it does, it must provide an implementation of ServiceConnection, which monitors the connection with the service. The bindService() method returns immediately without a value, but when the Android system creates the connection between the client and service, it calls onServiceConnected() on the ServiceConnection, to deliver the IBinder that the client can use to communicate with the service.
  • 11. Creating a Bind Service When creating a service that provides binding, you must provide an IBinder that provides the programming interface that clients can use to interact with the service. There are three ways you can define the interface: Extending the Binder class : If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind(). Using a Messenger : If you need your interface to work across different processes, you can create an interface for the service with a Messenger. In this manner, the service defines a Handler that responds to different types of Message objects. Using AIDL : AIDL (Android Interface Definition Language) performs all the work to decompose objects into primitives that the operating system can understand and marshall them across processes to perform IPC. The previous technique, using a Messenger, is actually based on AIDL as its underlying structure.
  • 12. Extending Binder Class If your service is used only by the local application and does not need to work across processes, then you can implement your own Binder class that provides your client direct access to public methods in the service. Here's how to set it up: 1. In your service, create an instance of Binder that either: 1. contains public methods that the client can call 2. returns the current Service instance, which has public methods the client can call 3. or, returns an instance of another class hosted by the service with public methods the client can call 2. Return this instance of Binder from the onBind() callback method. 3. In the client, receive the Binder from the onServiceConnected() callback method and make calls to the bound service using the methods provided.
  • 13. Using a Messenger If you need your service to communicate with remote processes, then you can use a Messenger to provide the interface for your service. This technique allows you to perform interprocess communication (IPC) without the need to use AIDL. Here's a summary of how to use a Messenger: 1. The service implements a Handler that receives a callback for each call from a client. 2. The Handler is used to create a Messenger object (which is a reference to the Handler). 3. The Messenger creates an IBinder that the service returns to clients from onBind(). 4. Clients use the IBinder to instantiate the Messenger (that references the service's Handler), which the client uses to send Message objects to the service. 5. The service receives each Message in its Handler—specifically, in the handleMessage() method.
  • 14. AIDL – Android Interface Definition Language AIDL (Android Interface Definition Language) allows you to define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC). On Android, one process cannot normally access the memory of another process. So to talk, they need to decompose their objects into primitives that the operating system can understand, and marshall the objects across that boundary for you.
  • 15. Steps in implementing AIDL in your program You must define your AIDL interface in an .aidl file using the Java programming language syntax, then save it in the source code (in the src/ directory) of both the application hosting the service and any other application that binds to the service. When you build each application that contains the .aidl file, the Android SDK tools generate an IBinder interface based on the .aidl file and save it in the project's gen/ directory. The service must implement the IBinder interface as appropriate. The client applications can then bind to the service and call methods from the IBinder to perform IPC. To create a bounded service using AIDL, follow these steps: 1. Create the .aidl file : This file defines the programming interface with method signatures. 2. Implement the interface : The Android SDK tools generate an interface in the Java programming language, based on your .aidl file. This interface has an inner abstract class named Stub that extends Binder and implements methods from your AIDL interface. You must extend the Stub class and implement the methods. 3. Expose the interface to clients : Implement a Service and override onBind() to return your implementation of the Stub class.
  • 16. 1. Creating a .aidl file // IRemoteService.aidl package com.example.android; // Declare any non-default types here with import statements /** Example service interface */ interface IRemoteService { /** Request the process ID of this service, to do evil things with it. */ int getPid(); /** Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); } Create a file with .aidl extention into the project/src folder. Write the file in above shown manner.
  • 17. 2. Implementing the interface in Service class When you build your application, the Android SDK tools generate a .java interface file named after your .aidl file. The generated interface includes a subclass named Stub that is an abstract implementation of its parent interface (for example, YourInterface.Stub) and declares all the methods from the .aidl file. private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public int getPid(){ return Process.myPid(); } public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) { // Does nothing } };
  • 18. 3. Exposing your interface to your clients Once you've implemented the interface for your service, you need to expose it to clients so they can bind to it. To expose the interface for your service, extend Service and implement onBind() to return an instance of your class that implements the generated Stub (as discussed in the previous section). Here's an example service that exposes the IRemoteService example interface to clients. public class RemoteService extends Service { @Override public void onCreate() { super.onCreate(); } @Override public IBinder onBind(Intent intent) { // Return the interface return mBinder; } private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public int getPid(){ return Process.myPid(); } public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) { // Does nothing } }; }