Will using getApplicationContext() in android avoid some memory leaks?

       First of all, the Context of the Activity and the Context of the Application are definitely not the same thing. One is the Context of the current activity, and its life cycle is limited to this activity, and the other is the Context of the entire application, and its life cycle accompanies the entire program. The characteristics of Context, abusing it often results in memory leaks, as shown in the following code:

public class TestContext{

    private static TestContext testContext;

    private Context context;


    private TestContext(Context context){

        this.context = context;

    }


    public static synchronized TestContext getInstance(Context context){

        if(null == testContext)

            testContext = new TestContext(context);

        return testContext;

    }

}

        Obviously, the textContext in the above singleton mode is a strong reference static type, and its life cycle often accompanies the entire application, but if the Context you pass in is an Activity, as long as our application is still alive, there is no way for it to work normally. Recycling, which results in a memory leak.

        The solution is very simple. Change the parameter context passed by initializing TestContext to context.getApplicationContext(), because the context of the application is obtained by this method, so there is no need to worry about memory leaks.

        If that's the case, wouldn't everyone be happy to replace context.getApplicationContext() where context can be used? Unfortunately, this is not possible, because they are not the same thing at all, their application scenarios are different, not all Activity Context scenarios, Application Context can still be used, here is a table I summed up, indicating Application scenarios between them:
https://pic3.zhimg.com/4c9656d1d4fa7556651829ba741df232_b.png



In fact, we only need to grasp two principles:

1. It is not recommended to use the Context of the Application for anything related to the UI.

2. Do not let objects with a long life cycle refer to the activity context, that is, ensure that the object that refers to the activity must have the same life cycle as the activity itself. If not, please consider whether you can use the Application context.

Reprinted from: http://www.zhihu.com/question/34007989/answer/58296467 

Guess you like

Origin blog.csdn.net/weixin_42602900/article/details/123084556