Detailed explanation of Android global context instance

Detailed explanation of Android global context instance

Context is required when toast start activity pops up, broadcast operation is sent, database usage notification is sent, etc

If the operation is carried out in the activity, it is very simple, because the activity itself is a context object

However, when the logical code is separated from the activity class, using context requires some skills:

We can customize our own application class to manage some global state information in the program, such as global context

The code is as follows:

Override the oncreate () method of the parent class and get the application level context by calling the getapplicationcontext () method

Then provide a static getcontext () method to return the retrieved context

Note: remember to initialize the myapplication class under the < Application > tab of the androidmanifest.xml file

In this way, the mechanism of global obtaining context is realized. To use context anywhere in the application, just call myapplication. Getcontext()

For example:

@H_ 301_ 38@Toast.makeText (myapplication. Getcontext(), "global context", toast. Length_short). Show();

If you use other Application, you can call other Application initialization methods in the OnCreate () method in MyApplication.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>