类似的问题一直是asked here,here和here,但背景与此截然不同,而且code that gave from this error是由Android和Android Studio的制造商编写的.
这是代码:
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache
cache = new LruCache(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public void addToRequestQueue(Request req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
发出警告的行是:
private static MySingleton mInstance;
private static Context mCtx;
现在,如果我删除static关键字,请更改public static synchronized MySingleton getInstance(Context … to public synchronized MySingleton getInstance(Context …错误disappers但是出现了另一个问题.
我在RecyclerView中使用MySingleton.所以这一行
@覆盖
public void onBindViewHolder(final RecyclerView.ViewHolder holder,int position){
ImageLoader imageLoader = MySingleton.getInstance(mContext).getImageLoader();
告诉我
Non-static method ‘getInstance(android.content.Context)’ cannot be refrenced from a static context.
请有人知道如何解决这个问题?
解决方法:
我引用
The quoted Lint warning is not complaining about creating singletons.
It is complaining about creating singletons holding a reference to an
arbitrary Context, as that could be something like an Activity.
Hopefully, by changing mContext = context to mContext =
context.getApplicationContext(), you will get rid of that warning
(though it is possible that this still breaks Instant Run — I cannot
really comment on that).
Creating singletons is fine, so long as you do so very carefully, to
avoid memory leaks (e.g., holding an indefinite static reference to an
Activity).
因此谷歌实际上并没有签约.要解决此问题,如果this.getApplicationContext作为上下文的参数提供,则不会发生内存泄漏.
所以实质上,忽略警告并提供this.getApplicationContext作为上下文的参数.
标签:android,java,android-volley,memory-leaks
来源: https://codeday.me/bug/20191005/1857445.html