Search code examples
androidmultithreadingbroadcastreceiverandroid-serviceandroid-broadcast

Separate thread background service with communication with activity in Android application


I'm an experienced Web-developer, but I'm very new to the Android SDK and Java. I have a conceptual question regarding background operations and multithreading in Android application.

I'm going to develop an app which will has a constantly-working background service (it will communicate with remote server over HTTP). Also, I'm going to have an activity that should display some status of the service, e.g. current operation and state.

So the idea is the following:

  1. When WIFI connects, the service should start, when WIFI disconnects, the service should stop. In other words, it should only work when there is an active wireless connection. I think I will need to implement an event handler of some kind to do so.

  2. The service should be running in a separate thread in order not to block the UI thread.

  3. Activity should be able to connect to the service and receive the status from it dynamically.

Of course, I'm not looking for a complete solution, just for some hints from an experienced professionals of what API components should I use.

Particularly, I'm interested in a safe way to run service in a separate thread and in the same time communicate with the activity. Any suggestions will be highly appreciated.


Solution

  • To answer your question point-wise:

    1. Create a custom BroadcastReceiver that intercepts the WIFI_STATE_CHANGED broadcast. Start the HTTP requests in its onReceive() method in a separate Service when connectivity is available.

    2. To perform HTTP requests, you can use either an IntentService OR a Service with AsyncTasks.

    3. Use a bound Service. This is actually not the best solution for this type of problem, but its a good starting point and can be refined later on.