Tips for global access to context

Source: Internet
Author: User

Tips for global access to Context

In Android Development, a context -sensitive object such as a popup Toast is used in many places:

When you need to start the activity, when you need to send the broadcast, when you need to operate the database, use the

When you know it, you need to wait.

If it is in Activity , it is easy to get the context object because the activity itself inherits Context, the direct benefit of this can be.

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

Here's a tip to tell you:

Android provides a application class that automatically moves the class when the application starts

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, you can specify it under the <application> tab of the androidmanifest.xml file , as shown in the code below:

<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.

So that we have implemented a global access to the Context of the mechanism, after no matter you want to be anywhere in the project

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.