简体   繁体   中英

Pass Application Context to the view instead of Activity Context

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());

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM