Android for any file access context

Source: Internet
Author: User

In Android programming, you should often encounter such a problem. Android requires a context to get the resources under RES, but it's not possible to write all of the code in the activity, and we've got some classes dedicated to dealing with different resources, That is to say, we may encounter other files through the context to get or change the state of the program, how should we get the context of the Android program in a Java file other than activity or inheriting activity?

We can define a class that defines an inherited application with a singleton pattern contextutils

Package Com.hcd.itetris.utils;import android.app.application;/** * Created is HCD on 14-11-8. * AUTHOR:JVAEYHCD */public class Contextutils extends application {    private static contextutils instance;    public static Contextutils getinstance () {        return instance;    }    @Override public    void OnCreate () {        super.oncreate ();        instance = this;    }}

The context of the Android program can be obtained from any location in the engineering code via Contextutils.getinstance ().

Attention:

You need to declare <application android:name= "Package-name in the Androidmanifest.xml file. Contextutils "/>

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "    package=" Com.hcd.itetris ">    <application        android:allowbackup=" true "        Android:icon = "@drawable/ic_launcher"        android:label= "@string/app_name"        android:theme= "@style/fullscreem"        Android:name= ". Utils. Contextutils ">        <activity            android:name=". Tetrisactivity "            android:label=" @string/app_name ">            <intent-filter>                <action android: Name= "Android.intent.action.MAIN"/>                <category android:name= "Android.intent.category.LAUNCHER"/>            </intent-filter>        </activity>    </application></manifest>


Android for any file access 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.