ServicesJintin
AGENDA
Definition
LifeCycle
Method
Manifest
Service Family
Close to You
Comparison
Q&A
Definition
Application Components
Activities
Services
Content Providers
Broadcast Receivers
What is not a Service..
not a separate process
not a Thread
What a Service is..
long running operation in background
no UI interaction
What a Service is..Context
Context Wrapper
Activity
ContextIml
Service
ContextThemeWrappe
Lifecycle
Two way Lifecycle
startService
bindService
both..
StartService
start by other Application Component (such like Activity, Service..) who calling startService
destroy by calling stopService() or stopSelf()
BindService
bind when Application Component calling bindService()
unbind when calling unbindService()
provide IBinder to interact with other component
when none is bind, the service destroy
Methods
Callback Methods
onStartCommand()
onBind()
onCreate()
onDestroy()
onStartCommand()
when Service is start by calling startService(), onStartCommand will be called
the Service will indefinitely running
you have to call stopSelf() or stopService() to destroy Service
onStartCommand()
wrap original onStart() before 2.0
return an Integer to indicate which behaviour to do when System killed it
onBind()
help to bind Service and other Application Component by ServiceConnection
return a IBinder instance to interact with other Component
return null to not allow binding
Service Connection
onServiceConnected (ComponentName name,IBinder service)
onServiceDisConnected (ComponentName name)
onCreate()
called before onStartCommand() and onBind()
won’t call if Service is already running
onDestroy()
called when the service is no longer used
should clean up all the resource such as thread, listener, receivers
Stop a Service
stopService(Intent intent)
stopSelf()
stopSelf(int startId)
Manifest
Manifest<manifest ... > ... <application ... > <service android:name=".MyService" /> ... </application> </manifest>
Manifest
support Intent Filter for implicit-Intent call
android:exported=”false” to forbid implicit-Intent call
Service Family
Intent Service
extends Service
auto generate worker thread
generate work queue to avoid multi-threading
Intent Service
auto stop Service when all request is done
default onBind() return null
default onStartCommand() redirect to onHandleIntent()
Close to You
Notify User
Toast Notifications
Status Bar Notifications
Foreground Service
more actively aware
less opportunity to been killed
startForeground() bind with an Notification for the status bar to interact with the user
like music player
Comparison
Service VS Activity
no UI
won’t killed when screen rotate
Process important hierarchy (killing priority)
more..
Service VS Thread
Main Thread or not
Context embedded
more..
Service VS Intent Service
Intent Service provide Worker queue that only allow one Thread to execute one time
more..
Thank you !
Email : [email protected]
Top Related