alockrem
alockrem

Reputation: 767

Android service not starting/stopping as expected

I have been given multiple solutions to what I thought would be a common scenario. Unfortunately, none seem to work as expected.

I have created a pretty simple android game. The users can invite friends to play and there are a few activities they are routed through during the game lifecycle. All turns and data is stored in a remote server which is exposing the data through web services. Every time an invitation is sent, or the opponents complete their turn, the user is prompted via the service to play their turn.

The service prompts the user using a standard android notification telling them it's their turn. I don't want the service to poll the web service or present notifications while the user is viewing the game (they'll already know if it's there turn).

I have tried the following solutions without any success.

  1. Start the service in the onPause method of the main activity and stop the service in the onResume method of the main activity.

    • Problem - Each time the user leaves the activity for another one the service starts. The user may be writing something or creating an invitation and they are prompted to take their turn.
  2. Bind each activity to the service and set a boolean (running) flag in the same onPause/onResume methods of all activities.

    • Problem - This seems logical, but for some reason the service never presents a notification. This is likely user-error, but I'm not sure this is the correct solution anyway.
  3. Start the service in the onPause method of all activities and stop the service in the onResume method of all activities.

    • Problem - Based on the toasts I'm presenting on the screen showing the state of the service this works as expected. The problem is the user is presented with notifications while the service is off. Apparently my toasts are misleading.

Any help is greatly appreciated. Sample code is not necessary, but would be appreciated if the solution is any more complex than the concept described above.

Thank you.

Upvotes: 1

Views: 201

Answers (1)

Kaediil
Kaediil

Reputation: 5535

Don't use a service, use the Google Cloud Messaging and in the receiver of the broadcast, check the state of the game and then decide whether or not to show the notification. Polling is generally bad, uses data and battery unnecessarily.

Upvotes: 1

Related Questions