Are there some ways to interact with services as simple as content providers’?
I mean, for example with content providers we have getContentResolver(): easy to query data if you have a Context. You even don’t have to worry about the details of cross-process calls (ContentProvider).
With services, you have to bind them, wait for connection to be established, then make sure to unbind them if you don’t want to leak the memory. Worse, you have to deal with AIDL for remote services.
Taking this example:
I have a file downloader module. Currently there are two approaches: content provider or service. To start every new download, it is easy for both:
- Service:
startService(). You just need a context. - Content provider:
getContentResolver()and insert the new download into its queue. You also just need a context.
But while the downloads are in progress, I want to obtain some information (average speed, percentage done…). The problem is here: a content provider is more easier to communicate with. Again you just need a context and query the information you want. In case of a service, you need to bind it, unbind it, or build your own AIDL (if it’s a remote service)…
I’m asking this question because with above example, a service seems to be the right approach over a content provider, at least because of its name.
Thanks,
Two ways I would suggest to do this…
The first is to try using ResultReceiver which implements
Parcelable.Basically create your own class which extends
ResultReceiverthen callputExtra(String name, Parceable valueon anIntentwhich you pass instartService(Intent intent)from yourActivity. TheServicecan then usesend(int resultCode, Bundle resultData)on theResultReceiverto send data back. If theResultReceiveris an inner class of yourActivityit will be able to interact with its UI.The second possibility is to use
Notificationsusing theFLAG_ONGOING_EVENTflag. This obviously wont appear in theActivityitself but will appear in theNotificationbar but you can create a customRemoteViewwith a progress and update text etc with each updated notification. This is similar to what you see when Google Play is installing or updating an app on your device.