Android service

8

Click here to load reader

Transcript of Android service

Page 1: Android service

Android Service

Page 2: Android service

Service● Application component that can perform long-running

operations in the background● Does not provide a user interface● Has more priority than hidden activity● Used on…

○ Media player○ File downloader○ etc

Page 3: Android service

● Life cycle○ Service starts running when

startService() / bindService() is called

○ Service is running even if called component is destroyed

○ It needs to be shutdown by stopService() / stopSelf()

Page 4: Android service

● Class extends android.Service● Runs on main thread of their hosting process● Android UI is also running on main thread, so to

handle UI actions while service, it needs to be running on seperate thread

Page 5: Android service

● startService○ Start single service which runs on background○ Cannot control. Only can check start/stop

MainActivity.java

LocalService.java

Page 6: Android service

● bindService○ bindService is for connecting

service to other component○ Needs to implement onBind

to send IBinder instance● Binder

○ Connect resource / class on other process

○ Allow to use method on other process

Page 7: Android service

● Call bindService from other component to connect on service

● Receive IBinder by onServiceConnected on ServiceConnection

● Control method on service by received instance

Page 8: Android service

● Return value of onStartCommand()

START_STICKY If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent.

START_REDELIVER_INTENT if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int)

START_NOT_STICKY If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent)