Android access to resources outside of activity
I would like to know - are there ways to access android resources and/or assets files (or files from any other folder) outside of an Activity (without passing context)?
Can't access without context:
getResources().getIdentifier("resource_name", "drawable", getPackageName());
getAssets().open("file_in_assets_folder_name");
Throws Exception if not in Activity:
try {
Class class = R.drawable.class;
Field field = class.getField("resource_name");
Integer i = new Integer(field.getInt(null));
} catch (Exception e) {}
Also tried the below, but it complains file doesn't exist (doing something wrong here?):
URL url = new URL("file:///android_asset/file_name.ext");
InputSource source = new InputSource(url.openStream());
//exception looks like so 04-10 00:40:43.382: W/System.err(5547): java.io.FileNotFoundException: /android_asset/InfoItems.xml (No such file or directory)
If the folders are included in the Project Build Path, you can use ClassLoader access files under them outside the android.content.Context, for instance, from a POJO (in case if you don't want to pass a reference of android.content.Context):
String file = "res/raw/test.txt";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
To add folders into Project Build Path, right click your project -- Build Path -- Configure Build Path, add your folder (for example, assets if using later SDK version) as a Source folder in build path.
Check out the similar question I answered before at here.
Android framework when compile your app create static class call:
your.namespace.project.R
you can statically call this class like:
your.namespace.project.R.string.my_prop
this.context.findViewById(your.namespace.project.R.id.my_id_prop);
Maybe you can access dynamic resources this way:
Resources res = this.context.getResources();
int id = res.getIdentifier("bar"+Integer.toString(i+1), "id", this.context.getPackageName());
链接地址: http://www.djcxy.com/p/59998.html
下一篇: Android访问活动之外的资源