In Android, you often encounter context-related content, most of which are passed as parameters, but what is the role of it?
Let's start with its usage, for example.
In the statement alertdialog.builder Builder = new Alertdialog.builder (this); , the parameter required to be passed is a context, where we pass in this, so what does this one refer to? Here this refers to the activity.this, which is the activity of this statement, which is the context of this activity. It's not right to have a lot of friends on the Internet passing in This.getapplicationcontext (). The Alertdialog object is dependent on a view, and the view is corresponding to an activity. So, here comes the question of a life cycle, This.getapplicationcontext () takes the context,activity.this of the application, which is the context of the Activity, the life cycle of which is different, the life cycle of the former is the entire application, the latter's life cycle is just its a Ctivity. And Alertdialog should belong to an activity, when the activity is destroyed it is destroyed, no longer exist; Into This.getapplicationcontext (), it means that its life cycle is the entire application, which clearly exceeds its life cycle. So, here we can only use the activity's this.
Here's a concrete explanation of its connotation.
In fact, Activity.this is a specific context, Activity.this is your current Activity, This.getapplicationcontext () Gets the context of the entire application, When you pass them as parameters, most of them are used to annotate which activity you want to operate in, such as the alertdialog.builder Builder = new Alertdialog.builder (this) mentioned above; You're going to create a dialog box in the current activity, if you're passing This.getapplicationcontext (), which is the context of the entire application, how does the code know which specific activity you want to create a dialog box in, so, What should be passed in here is the context of the activity in which you want to create the dialog box, that is, activity.this. If you understand that, then you should understand that each activity has its own context, and the entire application has only one context.
Summarize
Getapplicationcontext ()
Returns the context of the application, the entire application, and the application destroys it.
Activity.this
Returns the context of the current activity, and the life cycle is just the activity,activity that destroyed it.
Getapplicationcontext ()