Android Development Note "Context and Getapplicationcontext"

Source: Internet
Author: User

Context-related content is often encountered in Android

A brief discussion of the context: in the statement alertdialog.builder Builder = new Alertdialog.builder (this); , the parameter required to be passed is a context, where we are passing in this, then 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 a life cycle problem, This.getapplicationcontext () takes the context,activity.this of this application is the context of the Activity, the life cycle of the two is different , the life cycle of the former is the entire application, and the latter's life cycle is only the activity in which it resides. 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.

Error occurred with new Alertdialog.builder (Getapplicationcontext ()):

E/androidruntime (5844): android.view.windowmanager$badtokenexception:unable to add window--token null was not for a app Lication

Then looked up:

Getapplicationcontext () life cycle is the whole application, application destroy it to destroy Activity.this context belongs to activity, activity destroys he destroys

Activity.this to return an activity, getapplicationcontext () does not necessarily return an activity

Android Development Note "Context and Getapplicationcontext"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.