Android studio say static field will leak contexts

2019-07-13 00:23发布

Here is a similar question but I think it is not identical

And I read Setting up request queue tutorial here

In this page they write the following code

public class MySingleton {
   private static Context mCtx;

And I wrote same code in my project

public class VolleySingleton {
  private static Context mContext;

Android studio say “Do not place Android context classes in static fields; this is a memory leak”.
What does it mean? And why dos the official android developer website use such kind of code?

2条回答
何必那么认真
2楼-- · 2019-07-13 00:48

try this? `

class VolleySingleton {
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;
}`
查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-13 01:14

Android studio say static field will leak contexts

Let say You are referencing your class MySingleton from another class and your MySingleton Class has been destroyed by the OS but the static Context(mContext) is still in use by some activity so this will hold on the context from garbage collection unless you set your MySingleton reference inside your activity to null and this will leak all the application's resources

查看更多
登录 后发表回答