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