Difference between context [duplicate]

廉价感情. 提交于 2019-12-06 11:22:30

The application context is tied to the lifecycle of the application, and the Activity Context to the lifecycle of the Activity. So each one has its scope, and have to be used to retreive information at that level.

Normally, you should always use Acitity Context's, unless you need a context whose lifecycle is separate from the current Activity.

What can lead you to memory leaks, is the usage of Application Context, binding it to objects that should be garbage collected, but keeping this relevant attribute (the app context), they are being prevented from being collected.

Activity and Application are both derived from the Context class. Therefore, this can be used in place of a Context object when your code is part of either an Activity or Application class. Outside of one of these (in a Fragment, for example), you can call getActivity() to obtain the enclosing Activity (and use it as a Context). getApplicationContext() is how your Activity gets a Context broader than itself. You might want this if you need to use a Context beyond the lifetime of the Activity where you got it (for example, passing it into a long-running background thread).

You probably don't need the Application context in your Toast. But, by using it, your Toast should be able to remain visible and not cause any crashes even if you leave the Activity where you started it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!