What is 'Context' on Android?

前端 未结 30 2923
南旧
南旧 2020-11-21 04:46

In Android programming, what exactly is a Context class and what is it used for?

I read about it on the developer site, but I am unable to understand it

30条回答
  •  粉色の甜心
    2020-11-21 05:24

    The Context in Android is actually the context of what we are talking about and where we are currently present. This will become more clear as we go along with this.

    Few important points about the context:

    • It is the context of the current state of the application.
    • It can be used to get information regarding the activity and application.
    • It can be used to get access to resources, databases, and shared preferences, and etc.
    • Both the Activity and Application classes extend the Context class.

    Context is almost everywhere in Android Development and it is the most important thing in Android Development, so we must understand to use it correctly.

    Wrong use of Context can easily lead to memory leaks in an android application.

    As there are different types of context in Android, we as an Android Developer often get confused about which context to use at which place. So let’s understand what are those, how to use those, and when to use which one.

    Mainly two types of context:

    • Application Context: It is the application and we are present in Application. For example - MyApplication(which extends Application class). It is an instance of MyApplication only.
    • Activity Context: It is the activity and we are present in Activity. For example - MainActivity. It is an instance of MainActivity only.

    Application Context

    It is an instance that is the singleton and can be accessed in activity via getApplicationContext(). This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity.

    Example Use: If you have to create a singleton object for your application and that object needs a context, always pass the application context.

    If you pass the activity context here, it will lead to the memory leak as it will keep the reference to the activity and activity will not be garbage collected.

    In case, when you have to initialize a library in an activity, always pass the application context, not the activity context.

    You only use getApplicationContext() when you know you need a Context for something that may live longer than any other likely Context you have at your disposal.

提交回复
热议问题