Tips for global access to context

Source: Internet
Author: User

Tips for global access to Context

In Android Development, there are many places where context contexts are used , such as: Popup Toast

When necessary, when you need to launch the event, when you need to send the broadcast, when you need to operate the database, use the

When you know it, you need to wait.

Assuming that it is in Activity , it is very easy to get the context object because the activity itself inherits Context. The direct benefit of this is possible.

But for the more complex logic, the code is not in the Activity . So. Getting the Context is not so easy.

Here's a tip to tell you:

Android provides a application class. Each time the application starts, the system will voluntarily

To initialize.

And we can customize a application class to make it easier to manage some of the global state information in the program, such as the global context.

1, create a new class MyApplication inherit application.

The code is as follows:

Package Com.example.networktest;public class MyApplication extends application {    private static context context;    @Override public    void OnCreate () {        context = Getapplicationcontext ();    }    public static Context GetContext () {        return context;    }}


2, under the <application> tag of the androidmanifest.xml file to be able to specify, The code looks like the following:

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.example.networktest" Android : versioncode= "1" android:versionname= "1.0" >......<applicationandroid:name= " Com.example.networktest.MyApplication "... >......</application></manifest>

Note: Be sure to add the full package name when specifying MyApplication, or the system will not be able to find this

A class.

This way we have achieved a global access to the Context of the mechanism, and then whatever you want in the project, no matter where

Using Context, you just need to call Myapplication.getcontext () .


Tips for global access to context

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.