0

I have a MainActivity that calls a service. The service's onStart method loops until a specific variable is reached. When the variable is reached, I want the service to set off an alert to the user and bring the MainActivity to the screen so that the user can decide if they want to run the service again. Because it is a service, the MainActivity may already be in the foreground, or it may not have an instance of the activity at all. Either way, it should resume the first instance of MainActivity. I know I would have to use something such as an intent and FLAG_ACTIVITY_REORDER_TO_FRONT. I just do not know how I can implement the intent so that the MainActivity is brought to the foreground even if the user is in another app or has the app closed.

Update: The following link also helped with my problem as well. Thank you guys.

Example: Communication between Activity and Service using Messaging

Community
  • 1
  • 1

1 Answers1

0

The fact that your MainActivity calls a service does not mean that MainActivity will go out of focus. The Activity should remain in focus unless the user closes it or hits the "home" button. I wouldn't expect a service to cause an Activity to come into the foreground, it just sounds non-Android. If such a thing is actually allowed, I would expect the app to request permissions from the user to allow that to happen.

That said, your title suggests your looking to communicate with an Activity from a Service. To do that, you have a couple of options:

  1. Bind to the service via AIDL, and provide an AIDL callback to be called when the service needs to notify the Activity that something has occurred.
  2. Add a BroadcastReceiver to your Activity, and have the service send out an Intent to notify the Activity that something has occurred.

In either case, communication with the Activity should not cause it to come back into the foreground as that poses a security risk to the user. The app should not return to the foreground until the user either reopens it from the app drawer, or brings it back from recents.

bstar55
  • 3,346
  • 2
  • 18
  • 23
  • Thank you for your response @bstar55. If the service should not bring up an activity to the foreground, and I have the service notify the Activity to start a sort of alert or sound, what is the best way to notify the user where the alert is coming from and how to get back to the app quickly? Because I have working code, but it seems awkward to have an alert sound playing randomly. Would a simple notification suffice? Thanks again for the help. – user3700692 Jun 04 '14 at 21:54
  • In that case, you'd have the service display a Notification. This post covers that: http://stackoverflow.com/questions/1207269/sending-a-notification-from-a-service-in-android – bstar55 Jun 04 '14 at 21:56
  • Thanks! I'll need the AIDL as well for data I'd like to have the service give the activity. – user3700692 Jun 04 '14 at 22:03