1

Here, in this answer Activity instance is saved in WeakReference<Activity> variable. So that it will avoid memory leaks. Is it a good practice to do so?

public class BackgroundService extends IntentService {
    private static WeakReference<Activity> mActivityRef; 

    public static void updateActivity(Activity activity) {
        mActivityRef = new WeakReference<>(activity);
    }
}

I'm using mActivityRef.get() and casting it to required activity object. Using that object, accessing the methods in activity.

The purpose is to access Activity methods from service, this code does the work but as per the comments I'm confused whether to use it or not

I've referred the document yet not clear.

Prabs
  • 4,923
  • 6
  • 38
  • 59

2 Answers2

2

Is it a good practice to do so?

No.

The purpose is to access Activity methods from service

That activity may not exist. For example, the user could press BACK and destroy the activity while the service is running. Calling methods on a destroyed activity will likely lead to crashes.

Use an event bus (LocalBroadcastManager, greenrobot's EventBus, etc.) for loosely-coupled communications between components, such as between services and activities. Have the activity register for events when it is visible, and have the service post events as needed.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I've implemented [LocalBroadcastManager](https://stackoverflow.com/a/25172526/2820534) it is doing the task but can we trust this broadcast? will that be always addressed?? – Prabs May 24 '17 at 13:52
  • @Prabs: I do not know what you mean by "trust this broadcast" or "be always addressed". By definition, there may be nothing registered for some event. However, in that case, the service can find out about it and take other steps. For example, you can send a local broadcast, and if you have no foreground UI that picks up the event, the service can raise a `Notification` instead. See [this sample app](https://github.com/commonsguy/cw-omnibus/tree/v8.5/EventBus/LocalBroadcastManager). – CommonsWare May 24 '17 at 13:55
0

No its not a good practice to store a reference of Activity anywhere in your project but if you want do, create an interface implement your activity with interface and pass that interface as a communication way between your activity and IntentService to your service.

Now your service has a reference of your activity's (selected) methods. Access your data through that interface and clear reference after its usage.

Haris Qurashi
  • 2,104
  • 1
  • 13
  • 28