Android Xxxactivity and Getapplicationcontext () differences

Source: Internet
Author: User

From the touch of Android, everywhere can see the context of the figure, after viewing the source code you will find that it is only an abstract class, the implementation is implemented in Contextwrapper.

When you go to see the source of Android, you will find Activity,service and application are inherited from Contextwrapper, that is, they are the sub-class of the context, then we should give the context of the assignment?

A lot of times when you assign a value to a context in a acitivity, you pass it directly, This is the xxxactivity.this, that is, the context of xxxactivity, of course, when the beginning does not understand the time will be directly written Getapplicationcontext (), of course, the difference between the two is very obvious, Xxxactivity.this returns an instance of the current activity, Getapplicationcontext () returns an instance of application, with a much worse life cycle, application throughout the app, Life cycle of activity believe you are clear, so do not mess with, prevent memory leaks

1.dialog

dialog attached to the activity, so directly with the xxxactivity.this, when the activity disappears dialog also destroyed

2.activity

As we have said above, the direct use of Xxxactivity.this, the return is the current activity instance, the current activity is destroyed, together destroy

3.service,broadcastreceiver

Both are possible.

Summary: It is not recommended to use Getapplicationcontext (), which is related to UI operations, and generally uses the context associated with the activity, the rest of the operation, depending on the length of the life cycle of the existence of the choice


And I'm sorry, I'm not going to update the IM section yet, so let's look at this part of the camera and later update

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Xxxactivity and Getapplicationcontext () differences

Related Article

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.