How many types of context in android and what is better to use

前端 未结 2 1079
后悔当初
后悔当初 2021-02-05 12:20

I just wanted to know how many ways to get the context, which method used in which situation. Which one better to use, and what is the main and key deference between them.

2条回答
  •  遥遥无期
    2021-02-05 12:27

    Context class represents the local environment of an App, It encapsulates all the services and resources available to the app. There is a base class ApplicationContext, and sub classes for components: Activity, Service etc.

    Always prefer using ApplicationContext because it is global and doesn't cause serious issues if its leaked, that is: an unused reference of it stays and is not garbage collected.

    Sometimes you have to use sub components like Activity or Service as context. Use this when creating Intents, or creating UI Elements, or showing a toast etc. That is: functions that are specifically bound to these component's identity, its UI or its display window.

提交回复
热议问题