When to use the context of application, when to use the context of activity

Source: Internet
Author: User
Transfer from http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0526/2935.html
Single-case mode with application context
See if the period of use is within the activity cycle, if exceeded, must use application; Common scenarios include: Asynctask,thread, third-party library initialization, and so on.

There are also situations where you can only use activity: for example, dialog boxes, various view, startactivity, etc.

If the UI control needs to use activity as the context object, the default toast can actually be used with ApplicationContext.


It is important to note that some numbers have been added to the number, which is actually a yes in terms of ability, but why no. One explanation below:

Number 1: Starting the activity is possible in these classes, but a new task needs to be created. Generally not recommended.

Number 2: It is legal to go to layout inflate in these classes, but use the system default theme style If you customize some styles that might not be used.

Number 3: Allowed when receiver is null, in version 4.2 or later, to get the current value of the sticky broadcast. (Can be ignored)

Note: ContentProvider, broadcastreceiver in the above table, because there is a context in its internal method for use.

OK, here we look at the table, focusing on activity and application, you can see that the UI-related methods are not recommended or not to use application, and the first three operations are almost impossible to appear in application. In fact, as long as the grasp of a point, any UI-related, should use Activity as the context to deal with, and some other operations, service,activity,application and other instances can, of course, attention to the context of the holding of references, Prevent memory leaks.

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.