Use of Context in singleton memory leak problem
Brief introduction: So whenever you declare Context Context in a singleton, Do not place Android context classes in static fields (static reference to Single which has field mContext) pointing to Context); this is a memory leak (and also breaks Instant Run)
There may be a memory leak. Because the static class that you’re using in a singleton, you’re using the life cycle of your app, so using Context Context here is going to cause Context not to be recycled.
First, the original code
public class Single { private Context mContext; private static Single instance = null; Public static synchronized Single getInstance() {synchronized (single.class) {if (instance == null) { instance = new Single(); } } return instance; } public void init(Context context) { mContext = context; } public void getScreenWidth() { ScreenUtils.getScreenWidth(mContext); }}Copy the code
Second, solutions
Methods a
To replace the context with the context. GetApplicationContext (), at this time there will be prompted to memory leaks, many developers feedback is androidStudio bugs, if you don’t want to have this hint, need to ignore the warning, Add @SuppressLint(“StaticFieldLeak”) to variable
The complete code is as follows
public class Single { private Context mContext; @suppressLint ("StaticFieldLeak") private static Single instance = null; Public static synchronized Single getInstance() {synchronized (single.class) {if (instance == null) { instance = new Single(); } } return instance; } public void init(Context context) { mContext = context.getApplicationContext(); / / will ` context ` into ` context. GetApplicationContext () `} public void getScreenWidth () {ScreenUtils. GetScreenWidth (mContext); }}Copy the code
Method 2
Do not temporarily save the Context, in the case of need, just pass the method. The following code
public class Single { private static Single instance = null; Public static synchronized Single getInstance() {synchronized (single.class) {if (instance == null) { instance = new Single(); } } return instance; } public void getScreenWidth Context (Context) {/ / direct reference to the Context of ScreenUtils. GetScreenWidth (Context); }}Copy the code
I myself use the second method and add it
context.getApplicationContext()
Copy the code
Of course, you need to understand the difference between a context and an applicationContext and how the scenario will be used in your project.
Three, reference links
Stackoverflow.com/questions/3… Stackoverflow.com/questions/3…