8

I've come across this android code below. Is there ever a use case of creating a static weakreference object in a service to get its reference? I know that static variables are not eligible for Garbage collection. In general, Does creating a weak reference of any static variable change its gc properties?

for example:

private static WeakReference<MyService> mService;
public static MyService getInstance(){
    if(mService != null){
          return mService.get();
    } 
    return null;
}

And in my onCreate

public void onCreate(){
   super.onCreate();
   mService = new WeakReference<MyService>(this);
}
Daniel P
  • 83
  • 2
  • 3

1 Answers1

6

The WeakReference is so the service can be garbage collected even if the activity still has a variable referring to it. The static means it will persist after the activity ends. So you get a reference to the Service that persists between calls but still allow the Service to be gced. (The WeakReference itself can't be GCed, but shouldn't take much in the way of memory).

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127