Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
Service• Services are software components designed specifically
to perform long background operations.
• …such as downloading a file over an internet connection or streaming music to the user, but do not require a user interface.
• Services have a lifecycle that is separate from that of the component, such as an Activity, that starts them.
• This autonomy allows a service to continue running even after the starting component is no longer alive.
Service type
• Started Service• Something to be done in the background.• It doesn’t provide a result (although it can send a broadcast or set a
notification)• Started with context.startService(intent)• onBind() must return null
• Bound Service • Allows a client to set up a connection (bind) with the service so that
methods can be called• Started with context.bindService(intent,ServiceConnetcion,Flags)• onBind() returns an interface with methods that can be called
Starting the Service • The service to be started is identified via an intent,
provided as an argument of StartService(..) and bindService(..)
• Explicit intent are recommended• What about implicit intents? What happen if two services
respond to the same action?• The system selects one service at random (!)
• Given a higher priority can force the selection• Priority is a field of the <intent-filter> tag
Service class
java.lang.Object
android.content.Context
android.content.ContextWrapper
android.app.Service
android.app.Activity
android.content.BroadcastReceiver
android.content.ContextThemeWrapper
android.app.IntentService
Intent service• The IntentService class is a convenience class
(subclassed from the Service class) that sets up a worker thread for handling background tasks and handles each request in an FIFO order.
• Once the service has handled all queued requests, it simply exits.
• All that is required when using the IntentService class is to implement onHandleIntent(intent) method
Intent Service: example
• The service needs to be registered in the manifest file• The main activity creates an explicit intent pointing to the service • The service is started and the onHandleIntent method executed• Intents are queued and served serially
MainActivity
IntentService
Explicit Intent
Example• Suppose we want to sync with a local content provider
with a server, but only when an internet connection isavailable. This is one possible solution:
• Register a broadcast receiver to the following bcast intent:• ConnectionManager.CONNECTIVITY_ACTION• (When the connectivity changes this intent is fired)
• Check (from the receiver) if now the connection is now up• If this is the case, then start an IntentService• The IntentService will use a Socket to open a stream with
the server• Data are read from the content provider
Solution (sync)
BroadcastReceiver
IntentService
Start
ConnectivityManager.CONNECTIVITY_ACTIONContentProvider
Socket
Another example• Check a condition every minute..(warning: registration
must be dynamic, i.e. from inside an activity)
BroadcastReceiver
Intent Service
Start
Time tick
NotificationManager
Activity A
registerreceiver
Activity B
Create aPendingIntent
Another example (do something periodically)•
AlarmManager
Intent Service
PendingIntent
NotificationManager
Activity
Create a pending intentSet a periodic alarm
Activity
Another example (do something periodically). Solution 2
AlarmManager
Intent Service
PendingIntent
NotificationManager
Activity
Create a pending intentSet an alarm
Create a p.i,Set an alarm
Activity
Started service• Started services are launched by other application components
(such as an activity or even a broadcast receiver) and potentially run indefinitely in the background until the service is stopped, or is destroyed by the Android runtime system in order to free up resources.
• A service will continue to run if the application that started it is no longer in the foreground, and even in the event that the component that originally started the service is destroyed.
• By default, a service will run within the same main thread as the application process from which it was launched (referred to as a local service).
• It is important, therefore, that any CPU intensive tasks be performed in a new thread within the service
Started service• Unless a service is specifically configured to be private (once again via a setting
in the manifest file), that service can be started by other components on the same Android device.
• This is achieved using the Intent mechanism in the same way that one activity can launch another as outlined in preceding slides.
• Started services are launched via a call to the startService() method, passing through as an argument an Intent object identifying the service to be started.
• When a started service has completed its tasks, it should stop itself via a call to stopSelf().
• Alternatively, a running service may be stopped by another component via a call to the stopService() method, passing through as an argument the matching Intent for the service to be stopped.
• Services are given a high priority by the Android system and are typically amongst the last to be terminated in order to free up resource
Example• Let’s suppose we want run music in background• We can use the MediaPlayer class to play, for example,
an .mp3 file stored in the raw directory• The MediaPlayer has the create(context,id) method that
creates an istance of the MediaPlayer (say player) for the specified resource id
• A simple application will have two buttons (start and stop)• The start button will call the start method on the player…• The stop button will call the stop method on the player…
Example
Activity A
onCreate:player=MediaPlayer(ctx,R.raw.song)
startButton:player.start()
startButton:player.stop()
This solution is wrong…Why?
…Suppose the user kills the activity
And then starts the activity again….
If it clicks the start button a newinstance of the song is started…
Even worst the stop buttons doesn’tStop the previous song
Solution with started service
• An application that runs a player to play a song…
• The service is started from the Activity and then it spawns a thread
Service
UI Activity
Main Thread Play threadProcess
Solution with started service
startService(intent)
stopService(intent)
Activity is killed
onDestroy()
onStartCommand(…)
X
Activity is createdstartService(intent) onStartCommand(…)
A simple flag avoids to call another instance of MediaPlayer
Design guides• OnCreate –
• Called one time when the service is first started. This is where initialization code should be implemented.
• OnStartCommand –• Called for each request to start the service, either as a result of a call
to StartService or a restart by the system. • The method returns a StartCommmandResult value that indicates how
or if the system should handle restarting the service after a shutdown due to low memory. This call takes place on the main thread.
• OnDestroy –• Called after the service receives a StopSelf or StopService call. This is
where service-wide cleanup can be performed.
StartCommmandResult code• Sticky –
• A sticky service will be restarted, and a null intent will be delivered to OnStartCommand at restart.
• Redeliver Intent –• The service is restarted, and the last intent that was delivered to
OnStartCommand before the service was stopped by the system is redelivered.
• Not Sticky –• The service is not automatically restarted.
Foreground service• By default services are background, meaning that if the
system needs to kill them to reclaim more memory, they can be killed without too much harm.
• The method startForeground(id,Notification) • Makes a service run in the foreground state (meaning is less likely
to be killed by the OS), supplying the ongoing notification to be shown to the user while in this state.
• For example in the background music playback, the user would notice if the music stopped playing.
• Application can also acquire a ‘wake-lock’ (avoids the CPU to go in the idle state) and a wifi-lock (to avoid turning the radio off – if streaming is done from internet)
Bound Service (concept)• A bound service is similar to a started service with the
exception that it permits interaction with the component that launched it. • With a started service this could be partially achieved setting a specific
key in the intent to indicate some action to be performed (like, start the song again)
• However, a bound service allows the launching component to interact with, and receive results from, the service.
• Through the implementation of interprocess communication (IPC), this interaction can also take place across process boundaries.
Bound Service (clients)• A component starts and binds to a bound service via a call to
the bindService(intent,ServiceConnection,flag) method • Intent: identifies the service• ServiceConnection is an interface with two callback methods (called
when the connection to the service is established or lost)• Operation options for the binding (may be 0). See documentation
• Multiple components may bind to a service simultaneously.
• A component unbinds the service calling unbindService(ServiceConnection)• ServiceConnection is the same one used to bind
• When the last bound client unbinds from a service, the service will be terminated by the Android runtime system.
Bound Service (clients)• A bound Service is not a correct solution for playing music
in background. Why?• Hint: same problem as for the first solution (activity)
• However, a bound service may also be started via call to startService(…)
• Once started, components may then bind to it via bindService(..) calls
• When a bound service is launched via a call to startService(..) it will continue to run even after the last client unbinds from it
Bound Service (server)• A bound service extends the Servive class• It must include an implementation of the onBind() that returns
an object that implements IBinder (which is an interface) .• The object must extend the Binder class (that implements IBinder)
• A bound service can be local (belonging to the same package and running in the same process) or remote.
• In the case of local service the implementation is easier
• For remote service interprocess communication requires proxy and skeleton, plus the aild tool (see official documentation).
Bound Service (local service)• A service can be bounded to another SW component, meaning that it
can invoke methods implemented by the service through a proxy (Binder) of the Service (which is seen as a remote object)
• ServiceConnection is an interface monitoring connections to a service
Activity Service
ServiceConnection<<interface>>
1. bindService()
2. onBind()returns a referencethrough which calling methods
Remote services• It is possible to access a service running in a different
process
process A process B
skel
etho
nproxy
IDL
aidl
generates
tool
Service vs Thread • A service is a component that Android is aware of (it must
be declared in the manifest), with its own lifecycle
• A service can be activated from other components (not true for threads)
• A service is destroyed by the system only under very heavy circumstances and re-created according to restart options
• A service is in a sense similar to a Unix’s daemon, e.g, it can be used system-wide and started automatically after the device boot ends
Service process priority
• The system kills the process hosting a service if it is under heavy memory pressure.
• However, if this happens, the system will later try to restart the service (and a pending intent can be delivered again)
• A processes hosting service have higher priority than those running an activity