Android: How can I get the current foreground activity (from a service)?

前端 未结 12 1822
北恋
北恋 2020-11-22 07:53

Is there a native android way to get a reference to the currently running Activity from a service?

I have a service running on the background, and I would like to up

12条回答
  •  长发绾君心
    2020-11-22 08:43

    Is there a native android way to get a reference to the currently running Activity from a service?

    You may not own the "currently running Activity".

    I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?

    1. Send a broadcast Intent to the activity -- here is a sample project demonstrating this pattern
    2. Have the activity supply a PendingIntent (e.g., via createPendingResult()) that the service invokes
    3. Have the activity register a callback or listener object with the service via bindService(), and have the service call an event method on that callback/listener object
    4. Send an ordered broadcast Intent to the activity, with a low-priority BroadcastReceiver as backup (to raise a Notification if the activity is not on-screen) -- here is a blog post with more on this pattern

提交回复
热议问题