Pass Application Context to the view instead of Activity Context

南笙酒味 提交于 2019-12-12 09:48:13

问题


Why use Activity Context while we can use Application Context to load and access resource? Means if I use Application Context instead of Activity Context there is no Exception occur so why use Activity Context?

Example:

In below example if I use getApplicationContext() instead of "this" pointer inside the Activities onCreate() it works fine without any exception.

 Button button = new Button(getApplicationContext());

回答1:


getApplicationContext() should be used with the view, which will be having scope outside the Activity (An example of it might be when you bind to a Service from an Activity).

But for Defining Views like as you mentioned above (to define a Button), you should Definitely use Activity's Context (MyActivity.this or Simply this).

The reason for it is if you use getApplicationContext(), it will live as longer as the Whole Application lives. But for a Button, it should destroy as soon the Activity finishes, So it is always better to use this(Activity's Context), when defining such type of Views.

if I use Application Context instead of Activity Context there is no Exception

There is no exception because both are valid Contexts. Its upon you that if you keep your view alive for entire application lifetime, even if it is not needed (which would ultimately lead to Memory Leakages), or you want to destroy it with as soon as the Activity finishes.




回答2:


They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.

If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.

The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.

But in general, use the activity context unless you have a good reason not to.



来源:https://stackoverflow.com/questions/14079719/pass-application-context-to-the-view-instead-of-activity-context

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