That kind of callbacks (Observer pattern) that you are showing in your example won't work between a service and an activity. Use observer patter when, from class A, you created the instance of class B and want to send callbacks from B to A.
With regards to the services and activities, things are completely different. AFAICT, if you want to callback your Activity
from a Service
, the best method to achieve this is to use ResultReceiver
. There are a lot of interesting things about ResultReceiver
:
- Its constructor receives a
Handler
(that you must create inside the activity), which will allow you to change UI from the service.
- It implements
Parcelable
thus you can put a reference of your ResultReceiver
in the Intent
extras that you used to start the service.
- Its
onReceive
method has a result code integer which allows you to generate different kind of callbacks (this is like if your callback interface had many methods). Also, it receives a Bundle
which you can use to put all result data.
On the other hand, if you want to do a callback (not sure if that is correct term in this case), from your Activity
to your Service
, I guess you will have to send a Broadcast message or something like that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…