简体   繁体   中英

How to call activity from service

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM