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.

2 Answers 2

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.

2
  • I've implemented LocalBroadcastManager it is doing the task but can we trust this broadcast? will that be always addressed??
    – Prabs
    May 24, 2017 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. May 24, 2017 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.