0
  1. I started a Network Service from a "Splash Screen Activity". So, the context used inside this Service is the "Splash Screen Activity" context. OK.

  2. I dismiss the "Splash Screen Activity" and start the "Main Activity".

  3. The Network Service handles the Network traffic perfectly.

  4. Now, the Network Service needs to update the "Main Activity" with the received data.

The problem is that it needs a reference to the current activity ("Main Acitivity"). How can I retrieve the current Activity form the late "Splash Screen Activity"?

I thought in passing the "Main Activity" context through a Service's method and store it inside a variable, but as the Service is an abstract fully static class, I'm afraid to create a memory leak.

Any idea, how I can resolve this? Thanks

Greelings
  • 4,964
  • 7
  • 34
  • 70
  • 2
    "The problem is that it needs a reference to the current activity" -- no. It needs to raise an event that the current activity can pick up. A service should never have a reference to any activity, current or otherwise. Activities and services are loosely coupled. A typical implementation of this is to use an event bus, such as `LocalBroadcastManager` or greenrobot's EventBus. – CommonsWare Oct 20 '16 at 17:58
  • As an alternative to @CommonsWare comment, another suggestion is to just have your `Service` send a broadcast `Intent`, which the `Activity` can listen for. This also allows the 2 components to communicate without the `Service` having a reference to the `Activity`. – David Wasser Oct 23 '16 at 21:10
  • @DavidWasser: IMHO, using a system-level broadcast for this is not a great choice, due to performance (IPC overhead) and security (`registerReceiver()` by default accepts broadcasts from anyone). That's why I mentioned `LocalBroadcastManager` -- it gives you broadcast-style APIs without the performance hit or security issues. – CommonsWare Oct 23 '16 at 21:13
  • @CommonsWare. You are absolutely right. A service should never have a reference to any activity. But for a theoretical purpose, does a fragment stored in a *static attribute* of an *abstract class*, can lead to a memory leak? I don't think so. And you? – Greelings Oct 26 '16 at 15:51
  • A fragment knows its activity, so I presume that the fragment holds onto that in a field. In that case, holding a `static` reference to the fragment leaks the activity. An abstract class does not change that behavior. – CommonsWare Oct 26 '16 at 15:55
  • I found the solution here : http://stackoverflow.com/a/4739898/5607457 Simple and efficient. – Greelings Oct 28 '16 at 14:53

0 Answers0