SlideShare une entreprise Scribd logo
1  sur  17
Android
Services
Android Training
By Khaled Anaqwa
Android Services
 A service is a component which runs in the background without direct
interaction with the user. As the service has no user interface, it is not bound to
the lifecycle of an activity.
 Services are used for repetitive and potentially long running operations, i.e.,
Internet downloads, checking for new data, data processing, updating
content providers and the like.
 Services run with a higher priority than inactive or invisible activities and
therefore it is less likely that the Android system terminates them. Services can
also be configured to be restarted if they get terminated by the Android
system once sufficient system resources are available again.
 It is possible to assign services the same priority as foreground activities. In this
case it is required to have a visible notification active for the related service. It
is frequently used for services which play videos or music.
Services and background
processing
 By default a service runs in the same process as the
main thread of the application.
 Therefore you need to use asynchronous processing
in the service to perform resource intensive tasks in
the background. A common used pattern for a
service implementation is to create and run a new
Thread in the service to perform the processing in the
background and then to terminate the service once
it has finished the processing.
 Services which run in the process of the application
are sometimes called local services.
Starting and defining custom
services
 Custom services are started from other
Android components, i.e., activities,
broadcast receivers and other services.
Implementation and
declaration
 A service needs to be declared in the
AndroidManifest.xml file and the
implementing class must extend the
Service class or one of its subclasses.
In AndroidManifest.xml
<service
android:name="MyService"
android:icon="@drawable/icon"
android:label="@string/service_name"
>
</service>
Programmatically
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Start a service
 An Android component (service, receiver,
activity) can trigger the execution of a service
via the startService(intent) method.
// use this to start and trigger a service
Intent i= new Intent(context, MyService.class);
// potentially add data to the intent
i.putExtra("KEY1", "Value to be used by the
service");
context.startService(i);
Service start process and
execution
 When the startService(intent) method is called and
the service is not yet running, the service object is
created and the onCreate() method of the service is
called.
 Once the service is started, the startService(intent)
method in the service is called. It passes in the Intent
object from the startService(intent) call.
 When startService(intent) is called while the service is
running, its onStartCommand() is also called.
Therefore your service needs to be prepared that
onStartCommand() can be called several times.
Lifecycle
 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, by calling
stopSelf() or stopService(). (If you only want to
provide binding, you don't need to implement
this method.)
Lifecycle
 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.
 You must always implement this method, but if
you don't want to allow binding, then you
should return null.
Lifecycle
 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.
Lifecycle
 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.
What if you call startService
twice in your code?
 A service is only started once, no matter
how often you call the startService()
method.
Service restart behavior
 In its onStartCommand() method call, the service
returns an int which defines its restart behavior in
case the service gets terminated by the Android
platform.
 Service.START_STICKY:
Service is restarted if it gets terminated. Intent data passed to the
onStartCommand method is null.
 Service.START_NOT_STICKY:
Service is not restarted.
 Service.START_REDELIVER_INTENT:
Similar to Service.START_STICKY but the original Intent is
Re-delivered
check if the service was
restarted
 via the Intent.getFlags() method.
 START_FLAG_REDELIVERY (in case the
service was started with
Service.START_REDELIVER_INTENT) or
START_FLAG_RETRY (in case the service
was started with Service.START_STICKY) is
passed.

Contenu connexe

Tendances

Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
Jagdish Gediya
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
Ahsanul Karim
 
2010 08-26-smart-architecture
2010 08-26-smart-architecture2010 08-26-smart-architecture
2010 08-26-smart-architecture
CHIP
 
Login and private message
Login and private messageLogin and private message
Login and private message
gueste832a8e
 

Tendances (9)

Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Android Services and Managers Basic
Android Services and Managers BasicAndroid Services and Managers Basic
Android Services and Managers Basic
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
 
Transfer data from iPhone to iWatch
Transfer data from iPhone to iWatchTransfer data from iPhone to iWatch
Transfer data from iPhone to iWatch
 
Creating a mule project with raml and api
Creating a mule project with raml and apiCreating a mule project with raml and api
Creating a mule project with raml and api
 
Corespring
CorespringCorespring
Corespring
 
2010 08-26-smart-architecture
2010 08-26-smart-architecture2010 08-26-smart-architecture
2010 08-26-smart-architecture
 
Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...
 
Login and private message
Login and private messageLogin and private message
Login and private message
 

En vedette

Chapter 5 ms access-1
Chapter 5   ms access-1Chapter 5   ms access-1
Chapter 5 ms access-1
Pratik Gupta
 
Chapter 3 storage media and devices
Chapter 3   storage media and devicesChapter 3   storage media and devices
Chapter 3 storage media and devices
Pratik Gupta
 
Chapter 8 system analysis and design
Chapter 8   system analysis and designChapter 8   system analysis and design
Chapter 8 system analysis and design
Pratik Gupta
 
Introduction to Wi-Fi Direct
Introduction to Wi-Fi DirectIntroduction to Wi-Fi Direct
Introduction to Wi-Fi Direct
Wei-Tsung Su
 
C hapter 1 types-and_components_of_computer_system[1][1]
C hapter 1   types-and_components_of_computer_system[1][1]C hapter 1   types-and_components_of_computer_system[1][1]
C hapter 1 types-and_components_of_computer_system[1][1]
Pratik Gupta
 

En vedette (20)

Android training (android style)
Android training (android style)Android training (android style)
Android training (android style)
 
Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)
 
Android Training (Touch)
Android Training (Touch)Android Training (Touch)
Android Training (Touch)
 
Android Training (Notifications)
Android Training (Notifications)Android Training (Notifications)
Android Training (Notifications)
 
Chapter 5 ms access-1
Chapter 5   ms access-1Chapter 5   ms access-1
Chapter 5 ms access-1
 
Android Transition
Android TransitionAndroid Transition
Android Transition
 
Android Training (Animation)
Android Training (Animation)Android Training (Animation)
Android Training (Animation)
 
Uses of MS Access in Business
Uses of MS Access in BusinessUses of MS Access in Business
Uses of MS Access in Business
 
MS Access Training
MS Access TrainingMS Access Training
MS Access Training
 
Content provider in_android
Content provider in_androidContent provider in_android
Content provider in_android
 
Wi-Fi Direct
Wi-Fi DirectWi-Fi Direct
Wi-Fi Direct
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
 
Android Training (Content Provider)
Android Training (Content Provider)Android Training (Content Provider)
Android Training (Content Provider)
 
Wifi direct p2p app
Wifi direct p2p appWifi direct p2p app
Wifi direct p2p app
 
Android Sensor System
Android Sensor SystemAndroid Sensor System
Android Sensor System
 
Chapter 3 storage media and devices
Chapter 3   storage media and devicesChapter 3   storage media and devices
Chapter 3 storage media and devices
 
Chapter 8 system analysis and design
Chapter 8   system analysis and designChapter 8   system analysis and design
Chapter 8 system analysis and design
 
Introduction to Wi-Fi Direct
Introduction to Wi-Fi DirectIntroduction to Wi-Fi Direct
Introduction to Wi-Fi Direct
 
Smartphone sensor and gesture
Smartphone sensor and gestureSmartphone sensor and gesture
Smartphone sensor and gesture
 
C hapter 1 types-and_components_of_computer_system[1][1]
C hapter 1   types-and_components_of_computer_system[1][1]C hapter 1   types-and_components_of_computer_system[1][1]
C hapter 1 types-and_components_of_computer_system[1][1]
 

Similaire à Android Training (Services)

Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
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
 
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
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
Muhammad Sajid
 
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
 

Similaire à Android Training (Services) (20)

Services I.pptx
Services I.pptxServices I.pptx
Services I.pptx
 
Android service and gcm
Android service and gcmAndroid service and gcm
Android service and gcm
 
Android101
Android101Android101
Android101
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 Services
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
 
Android Services
Android ServicesAndroid Services
Android Services
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
AIDL - Android Interface Definition Language
AIDL  - Android Interface Definition LanguageAIDL  - Android Interface Definition Language
AIDL - Android Interface Definition Language
 
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
 
Unit2
Unit2Unit2
Unit2
 
Andriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptxAndriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptx
 
Android application development
Android application developmentAndroid application development
Android application development
 
Android building blocks and application life cycle-chapter3
Android building blocks and application life cycle-chapter3Android building blocks and application life cycle-chapter3
Android building blocks and application life cycle-chapter3
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdf
 
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 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changes
 
Ppt 2 android_basics
Ppt 2 android_basicsPpt 2 android_basics
Ppt 2 android_basics
 
Aidl service
Aidl serviceAidl service
Aidl service
 

Plus de Khaled Anaqwa (7)

Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 
Android Training (Sensors)
Android Training (Sensors)Android Training (Sensors)
Android Training (Sensors)
 
Android Training (Media)
Android Training (Media)Android Training (Media)
Android Training (Media)
 
Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)
 
Android Training (Android UI)
Android Training (Android UI)Android Training (Android UI)
Android Training (Android UI)
 
Android Training (Intro)
Android Training (Intro)Android Training (Intro)
Android Training (Intro)
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Android Training (Services)

  • 2. Android Services  A service is a component which runs in the background without direct interaction with the user. As the service has no user interface, it is not bound to the lifecycle of an activity.  Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.  Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them. Services can also be configured to be restarted if they get terminated by the Android system once sufficient system resources are available again.  It is possible to assign services the same priority as foreground activities. In this case it is required to have a visible notification active for the related service. It is frequently used for services which play videos or music.
  • 3. Services and background processing  By default a service runs in the same process as the main thread of the application.  Therefore you need to use asynchronous processing in the service to perform resource intensive tasks in the background. A common used pattern for a service implementation is to create and run a new Thread in the service to perform the processing in the background and then to terminate the service once it has finished the processing.  Services which run in the process of the application are sometimes called local services.
  • 4. Starting and defining custom services  Custom services are started from other Android components, i.e., activities, broadcast receivers and other services.
  • 5. Implementation and declaration  A service needs to be declared in the AndroidManifest.xml file and the implementing class must extend the Service class or one of its subclasses.
  • 7. Programmatically public class MyService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { //TODO do something useful return Service.START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { //TODO for communication return IBinder implementation return null; } }
  • 8. Start a service  An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method. // use this to start and trigger a service Intent i= new Intent(context, MyService.class); // potentially add data to the intent i.putExtra("KEY1", "Value to be used by the service"); context.startService(i);
  • 9. Service start process and execution  When the startService(intent) method is called and the service is not yet running, the service object is created and the onCreate() method of the service is called.  Once the service is started, the startService(intent) method in the service is called. It passes in the Intent object from the startService(intent) call.  When startService(intent) is called while the service is running, its onStartCommand() is also called. Therefore your service needs to be prepared that onStartCommand() can be called several times.
  • 10.
  • 11. Lifecycle  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, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method.)
  • 12. Lifecycle  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.  You must always implement this method, but if you don't want to allow binding, then you should return null.
  • 13. Lifecycle  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.
  • 14. Lifecycle  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.
  • 15. What if you call startService twice in your code?  A service is only started once, no matter how often you call the startService() method.
  • 16. Service restart behavior  In its onStartCommand() method call, the service returns an int which defines its restart behavior in case the service gets terminated by the Android platform.  Service.START_STICKY: Service is restarted if it gets terminated. Intent data passed to the onStartCommand method is null.  Service.START_NOT_STICKY: Service is not restarted.  Service.START_REDELIVER_INTENT: Similar to Service.START_STICKY but the original Intent is Re-delivered
  • 17. check if the service was restarted  via the Intent.getFlags() method.  START_FLAG_REDELIVERY (in case the service was started with Service.START_REDELIVER_INTENT) or START_FLAG_RETRY (in case the service was started with Service.START_STICKY) is passed.