在某些应用中,为了实现应用apk资源放入重复利用,或者使用反射得到本应用的资源,需要使用反射反射方式获得,但Resources类中也自带了这种获取方式,并且功能更加强大
注意,这里说的资源是静态资源,即媒体文件
android.content.res.Resources.class
public int getIdentifier(String name, String defType, String defPackage) {
if (name == null) {
throw new NullPointerException("name is null");
}
try {
return Integer.parseInt(name);
} catch (Exception e) {
// Ignore
}
return mAssets.getResourceIdentifier(name, defType, defPackage);
}
1.如下,我们可以获取当前应用的资源id
int drawableId = mContext.getResources().getIdentifier("ic_launcher","drawable", mContext.getPackageName());
mImageView.setImageResource(drawableId);
2.我们也可以获取其他应用的资源id
Resources resources = context.getResources();
int indentify= getResources().getIdentifier("icon", "drawable", "org.anddev.android.testproject");
对于这种方式,我们也可以这么做
int indentify = getResources().getIdentifier(org.loveandroid.androidtest:drawable/icon",null,null);
3.进行封装一下
public static int getResourceId(Context context,String name,String type,String packageName){
Resources themeResources=null;
PackageManager pm=context.getPackageManager();
try {
themeResources=pm.getResourcesForApplication(packageName);
return themeResources.getIdentifier(name, type, packageName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return 0;
}
android系统中,应用的资源存储时也通常会被存入 数据库,也可以被共享,因此来说资源会获得应用的uri
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.xinyueshenhua);
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.drawable.ic_launcher);
我们也可以进一步封装
public static Uri getResourceUri(int resId,String packageName)
{
return Uri.parse("android.resource://"+packageName+"/"+resId);
}
原文:http://my.oschina.net/ososchina/blog/353692