38
SERVICES

8 SERVICES 18 - uniroma1.itberaldi/MACC_18/08.pdf · Service vs Thread • A service is a component that Android is aware of (it must be declared in the manifest), with its own lifecycle

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

SERVICES

Services• A Service is an application component that runs in background,

not interacting with the user, for an indefinite period of time.

• Services, like other application objects (activities, broadcast receivers…), run in the main thread of their hosting process.

• This means that, if a service is going to do any CPU intensive operation (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.

• So what is the difference between Threads and Services?

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 is destroyed by the system only under very heavy circumstances and re-created according to the restart options

• A service is in a sense similar to a Unix’s daemon, e.g, it can be used system-wide (e.g., from other applications) and for example be started automatically after the device boot ends

• Android platform provides a set of system wide services• getSystemService()

Some example of system service• AccessibilityManager, for being notified of key system events (e.g., activities starting) that might be relayed to users via haptic

feedback, audio prompts, or other non-visual cues• AccountManager, for working with Android’s system of user accounts and synchronization• ActivityManager, for getting more information about what processes and components are presently running on the device• AlarmManager, for scheduled tasks (a.k.a., “cron jobs”), covered elsewhere in this book• AppOpsManager, for “tracking application operations on the device”• AppWidgetManager, for creating or hosting app widgets• AudioManager, for managing audio stream volumes, audio ducking, and other system-wide audio affordances• BatteryManager, for finding out about the state of the battery• BluetoothManager, for exposing or connecting to Bluetooth services• ClipboardManager, for working with the device clipboard, covered elsewhere in this book• ConnectivityManager, for a high-level look as to what sort of network the device is connected to for data (e.g., WiFi, 3G)• ConsumerIrManager, for creating “IR blaster” or other IR-sending apps, on hardware that has an IR transmitter• DevicePolicyManager, for accessing device administration capabilities, such as wiping the device• DisplayManager, for working with external displays, covered elsewhere in this book• DownloadManager, for downloading large files on behalf of the user, covered in elsewhere in the book• DropBoxManager, for maintaining your own ring buffers of logging information akin to LogCat• FingerprintManager, for working with fingerprint readers on Android 6.0+ devices• InputMethodManager, for working with input method editors• InputManager, for identifying external sources of input, such as keyboards and trackpads• JobScheduler, for scheduling periodic background work, covered elsewhere in the book• KeyguardManager, for locking and unlocking the keyguard, where possible• LauncherApps, for identifying launchable apps on the device (e.g., for home screen launchers), taking into account device

policies• LayoutInflater, for inflating layout XML files into Views, as you saw earlier in the book• LocationManager, for determining the device’s location (e.g., GPS), covered in the chapter on location tracking• MediaProjectionManager, for capturing screenshots and screencasts• MediaRouter, for working with external speakers and displays• MediaSessionManager, for teaching Android about media that you are playing back

Some example of system service• MidiManager, for playing MIDI audio• NetworkStatsManager, “for querying network usage stats”• NfcManager, for reading NFC tags or pushing NFC content• NotificationManager, for putting icons in the status bar and otherwise alerting users to things that have occurred

asynchronously, covered in the chapter on Notification• NsdManager, for network service discovery operations• PowerManager, for obtaining WakeLock objects and such, covered elsewhere in this book• PrintManager, for printing from Android• RestrictionsManager, for identifying and working with restricted operations• SearchManager, for interacting with the global search system• SensorManager, for accessing data about sensors, such as the accelerometer, covered elsewhere in this book• StorageManager, for working with expanded payloads (OBBs) delivered as part of your app’s installation from the Play Store• SubscriptionManager, for dealing with data roaming and other telephony subscription rules• TelecomManager, for dealing with incoming and outgoing phone calls• TelephonyManager, for finding out about the state of the phone and related data (e.g., SIM card details)• TextServicesManager, for working with spelling checkers and other “text services”• TvInputManager, for Android-powered televisions, to find out about TV inputs• UiModeManager, for dealing with different “UI modes”, such as being docked in a car or desk dock• UsageStatsManager, “for querying device usage stats”• UsbManager, for working directly with accessories and hosts over USB• UserManager, for working with multiple user accounts on a compatible device (Android 4.2+ tablets, Android 5.0+ phones)• Vibrator, for shaking the phone (e.g., haptic feedback)• WallpaperService, for working with the device wallpaper• WifiManager, for getting more details about the active or available WiFi networks• WifiP2pManager, for setting up and communicating over WiFi peer-to-peer (P2P) networks• WindowManager, mostly for accessing details about the default display for the device

Service types: Foreground services• A foreground service performs some operation that is

noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a status bar icon. • startForeground(id,Notification) method

• The system rarely kills a Foregroud Service

• However, if the user wants to listen the music only when interacting with the app, a thread is to be used

• One create a thread in onCreate(), start running it in onStart(), and stop it in onStop(). [source: developer site]

Service types: Background services• A background service performs an operation that isn't directly

noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

• The system is more likely to kill a background service than a foreground one

• Stating from Oreo, for performance reasons the system imposes restrictions on running background services when the app itself is not in the foreground.

• The Scheduled Job is recommended for performing background operations [see later]

Service behavior: Started Service• It has a lifecycle that's independent of the component that

started it.

• Performs a single operation

• Does not return the result to the caller directly

• The service can run in the background indefinitely, even if the component that started it is destroyed. • Not killed by the sytem when they finish their job

• The Android platform may not support started services in the future! [source: developer site]

Service behavior: Bounded Services• A bound service offers a client-server interface that allows

components to interact with the service, send requests, receive 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.

• A service can exhibit both behaviors.

Service lifecycle

Mixing Bound and Unbouded services

How to use a started service• 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.

• It can be called several times (but the service is created once)

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

• Warning: the service runs inside the main thread

How to implement a started service• Extending the base Service class• Implement the onStartCommand(Intent, flags, startId)

method• (Separate thread for CPU intensive blocking operations)

• Return • START STICKY - restart faster• START NOT STICKY - killed faster

• Implement onBind() is mandatory - return null

Example of code

Example• Let’s suppose we want run music in background, i.e., user

do not interact with the application• 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…

Solution with started service

Service PlayerUI Activity(startService)

Main Thread

Process

intent

Solution with started service

Service Player

Main Thread

Process

Solution with started service

Service PlayerUI Activity(stopService)

Main Thread

Process

intent

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.

• OnDestroy –• Called after the service receives a StopSelf or StopService call.

This is where service-wide cleanup can be performed.

Putting service in foreground• Allows a service to be considered as ‘visibile’ to the user

(less probability it is killed)

• For example in the background music playback, the user would notice if the music stopped playing.

• Once the service has been created, the service must call its startForeground(id,Notification) method within five seconds.

Bound services

• 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

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.

• A bound service allows the launching component to interact with, and receive results from, the service.

• Through the implementation of interprocesscommunication (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• 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• Override its two methods

Activity ServiceServiceConnection 1. bindService()

onBind()returns a referencethrough which calling methods

Interface

Example

Service’s public methods are available to the client

Example

mSevice. getRandomNumber()

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 subtypes• Scheduled (new, added in Android 5.0)• Allows for scheduling service with different requirements• When the conditions are met the Service is executed• As usually, user must override predifined methods

• E.g., onStartJob(), onStopJob()

JobScheduler• Used when a task do not require an exact time, but it could be

scheduled based on a combination of system and user requirements.

• For example, a news app might like to update the news in the morning, but could wait until the device is charging and connected to wifi to update the news, to preserve the user's data and system resources.

• The JobScheduler class allows for setting the conditions, or parameters of running the task.

• The JobScheduler calculates the best time to schedule the execution of the job.

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

Services and broadcast receivers

• Suppose we want to check a remote server only when an internet connection becomes available.

• 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 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

Solution

BroadcastReceiver

IntentService

Start

ConnectivityManager.CONNECTIVITY_ACTION

Socket

Send a notification

Another example• The main activity starts the service and registers a

receiver. • The service is slow, therefore it runs in a parallel thread its

time consuming task. • When done with a computing cycle, the service adds a

message to an intent. • The intent is broadcasted using the filter: xxxxx• BroadcastReceiver (defined inside the main Activity) uses

the previous filter and catches the message (displays the contents on the main UI ).

• At some point the main activity stops the service and finishes executing.

Another example (do something periodically)• 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

Set a periodic alarm

Activity