Use interface to provide Android context for singleton?

徘徊边缘 提交于 2019-12-14 03:06:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!