活动以外的Andr​​oid获取资源资源、Andr、oid

由网友(骚的像逼)分享简介:我想知道 - 是有办法(从任何其他文件夹或文件)访问Android的资源和/或资产的文件的活动以外(的没有通过上下文的)? 可以没有上下文无法访问:getResources()则getIdentifier(RESOURCE_NAME,绘制,getPackageName())。getAssets()开(file_in_...

我想知道 - 是有办法(从任何其他文件夹或文件)访问Android的资源和/或资产的文件的活动以外(的没有通过上下文的)?

可以没有上下文无法访问:

  getResources()则getIdentifier(RESOURCE_NAME,绘制,getPackageName())。
getAssets()开(file_in_assets_folder_name)。
 

抛出异常,如果不是在活动:

 尝试{
    类= R.drawable.class;
    场场= class.getField(RESOURCE_NAME);
    整数i =新的整数(field.getInt(空));
}赶上(例外五){}
 

也试过以下,但它抱怨文件不存在(在这里做得不对?):

 网​​址URL =新的URL(文件:///android_asset/file_name.ext);
的InputSource源=新的InputSource(url.openStream());
//例外,看起来像这样04-10 00:40:43.382:W / System.err的(5547):java.io.FileNotFoundException:/android_asset/InfoItems.xml(没有这样的文件或目录)
 

解决方案

如果该文件夹包含在项目构建路径,你可以使用的的ClassLoader 访问下他们,如果你不希望文件android.content.Context之外,例如,从一个POJO(如遇通过android.content.Context的引用):

 字符串文件=RES /生/ test.txt的;
InputStream的时间= this.getClass()getClassLoader()的getResourceAsStream(文件)。;
 

在res文件夹包含到默认项目构建路径,所有的Andr​​oid SDK版本至今。 资产文件夹被列入到默认的Andr​​oid SDK之前的R14项目构建路径。

要添加文件夹到项目构建路径,右击你的项目 - 构建路径 - 配置构建路径,添加文件夹(例如,如果资产使用后的SDK版本)作为构建路径中的源文件夹

检查出类似的问题,我之前在here.

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);

The res folder is included into Project Build Path by default by all Android SDK version so far. The assets folder was included into Project Build Path by default before Android SDK r14.

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.

阅读全文

相关推荐

最新文章