问题
I've been looking through the forks of a popular library that keep an ApplicationContext as a member field within a singleton. This make the app memory intensive as the process is a bit expensive. Some forks claim to solve the problem by using an anonymous class implement an interface to provide the Context for the singleton in demand (here and here). In general, the code can be summarized like this:
The interface:
public interface FFbinaryContextProvider {
Context provide();
}
The singleton:
public class FFmpeg implements FFbinaryInterface {
private final FFbinaryContextProvider context;
private static FFmpeg instance = null;
private FFmpeg(FFbinaryContextProvider context) {
this.context = context;
}
public static FFmpeg getInstance(final Context context) {
if(instance == null) {
instance = new FFmpeg(new FFbinaryContextProvider() {
public Context provide() {
return context;
}
});
}
return instance;
}
//get the context like this this.context.provide()
}
}
An then invoke the singleton within the Acitivity like this FFmpeg.getInstance(this);
I'm not familiar with this approach. Is it just by hiding the Context under an interface like this would allow the garbage collector to collect it whenever the activity get killed? Is there any resource that I can read more on this matter?
And while we are at it, if the aim is to prevent memory leaks, doesn't WeakReference already solve this issue? Is there any downside with using a WeakReference within a singleton?
来源:https://stackoverflow.com/questions/48161708/use-interface-to-provide-android-context-for-singleton