How to write Android Service?

How to write Android Service?


Table of Contents

  • Two kinds of Services in Android
  • Local Service
  • Remote Service
  • Broadcast

1 Two kinds of Services in Android

When we wanna make an Android app, we should put the time-consuming jobs into a service, actually, there are two kinds of services in Android, Local Service, and Remote Service. The difference between them is that whether they are running in the same process as the app, the local Services are running in the same process as the app, while the remote Services are running in the separate process, and I just need to add the following attribute to the AndroidManifest declaration to announce a remote service, it is a local Service without this attribute.
android:process=":remote"
After We build the Service, We need to communicate with this object, send a message to Service is obvious, I just need to bind to that Service. But how to receive announcement and messages from the Service, the mechanisms to do it are different according to the types of Services. Actually, that's all depend on whether the communication is in the same process or not.
So, the primary topic of this article is about how to send a message back to Activity from the Service.

2 Local Service

Since local Service is running in the same process as the Activity, so, I think the Android's IPC mechanism, Binder, is not needed, I just need to register a callback function to the Service, I think that's the most simple way. Following is an example I made to demonstrate it.

https://github.com/suzp1984/parrot/tree/master/android_app/Service/LocalServiceSample

3 Remote Service

Android's IPC mechanism must be employed in this situation, there are two ways: use Remote Callback aidl interface and use Messenger. There is a little-complicated source code at this scenario, but there is pattern behind it, it should not be so hard to learn.

I upload the source code, implemented both Callback aidl and Messenger ways, into the following link. Parts of them are referred to the Android's Apidemo example.

https://github.com/suzp1984/parrot/tree/master/android_app/Service/RemoteServicesSample

4 Broadcast

There is another way to send a callback to the Activity by just send a broadcast intent. But I don't why, but register BroadcastReceiver in the Activity and send Broadcast in the Service seems not dependable, sometimes, the activity missed all Broadcast intent, maybe I need to understand Broadcast more to figure out the reason, and the correct ways to use Broadcast. And that's why I studied the communication between Service and Activity and wrote this article.

Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp