Karyuu Ouji Karyuu Ouji - 1 year ago 58
Java Question

How to best do this in android?

I am thinking of making an app that interacts with a Web API.


  1. Start the bet and Display notification

  2. Send the bet to the site via POST.

  3. When the result arrives, update UI with the result.

  4. If the user hasn't pressed the stop button, back to #2 else stop the bet and remove notification.

  5. If the app is closed or not the active app, the betting would still continue

  6. If the notification is clicked, show/start the app

After a lot of research and reading, I thought that the bound foreground service would accomplish this, but I can't find (or maybe I just don't understand) how doing it...

Here are my questions:

If I make a service and put the logic of betting in it, my activity/app would start the service and bind with it..

  1. How can I tell the service to start betting with the initial bet data from the activity?

  2. How can the service know when the app closes or is not the active app on screen?

  3. How can the service update the UI of the app?

I will still search for a possible way to do this. I hope someone can guide me to the right way..


(3) I ended up using
to signal the App components from the service of when to update the UI.

(2) By using
, I thought that my service should not mind the my App's State.

(1) I used
Bound Service
and just call method on the service to pass data and start betting.

Answer Source

You send data to service via Intent: http://stackoverflow.com/a/15899750/3423468

Intent serviceIntent = new Intent(YourService.class.getName());
serviceIntent.putExtra("data", "123456");

Then in Service override OnStartCommand method:

public int onStartCommand (Intent intent, int flags, int startId)
   String userID = intent.getStringExtra("data");
   return START_STICKY;//or non-sticky

For handling app close event you can check this answer(never used myself): http://stackoverflow.com/a/26882533/3423468

And regarding your last question, you can use BroadcastReciever to send data from service to activity and update UI

For further reading check this links:

  1. Services Tutorials
  2. Official Developers Guide To Services
  3. BroadCastReceivers Tutorial
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download