Android Xxxactivity and Getapplicationcontext () differences

Source: Internet
Author: User

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

When you go to view the source code of Android, you will find activity. Both service and application inherit from Contextwrapper. That is, they are all sub-classes of the context, then how should we give the context assignment?

Very often when assigning a value to the context in acitivity, this is the xxxactivity.this. That is the context of xxxactivity. Of course, when you start to do not understand the time will directly write Getapplicationcontext (), of course, the difference between the two is very obvious, Xxxactivity.this returns the current activity instance. Getapplicationcontext () Returns an instance of application, which has a very poor life cycle, application throughout the App,activity life cycle believe you are very clear, so do not use, to prevent memory leaks

1.dialog

dialog is dependent on activity existence. So just use xxxactivity.this, and when the activity disappears, dialog will destroy it.

2.activity

As we have said above, use xxxactivity.this directly. The current activity instance is returned, and when the activity is destroyed, it is destroyed together.

3.service,broadcastreceiver

Both are able to

Summary: It is not recommended to use Getapplicationcontext (), which is related to UI operations, and generally uses context related to activity. The rest of the operation, see details, based on the length of the life cycle to make choices


There is also very sorry, temporarily do not intend to update the IM part, first study this part of the camera. Post-Update

Android Xxxactivity and Getapplicationcontext () differences

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.