In some applications, in order to implement the application of the APK resource into the reuse, or use reflection to get the resources of the application, it needs to be obtained by reflection reflection, but the resource class also comes with this method, and the function is more powerful
Note that the resources mentioned here are static resources, that is, media files
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, Defpackag e); }
I. Getting the ID of a resource
1. Below, we can get the resource ID of the current app
int drawableid = Mcontext.getresources (). Getidentifier ("Ic_launcher", "drawable", Mcontext.getpackagename ()); Mimageview.setimageresource (Drawableid);
2. We can also get the resource ID of other apps
Resources resources = context.getresources (); int indentify= getresources (). Getidentifier ("icon", "drawable", " Org.anddev.android.testproject ");
In this way, we can do the same.
int indentify = Getresources (). Getidentifier (Org.loveandroid.androidtest:drawable/icon ", null,null);
3. Carry out the package
public static int Getresourceid (Context context,string name,string type,string packagename) {Resources THEMERESOURC Es=null; Packagemanager Pm=context.getpackagemanager (); try {themeresources=pm.getresourcesforapplication (packagename); Return Themeresources.getidentifier (name, type, packagename); } catch (Namenotfoundexception e) {e.printstacktrace (); } return 0; }
Two. Get the URI of the resource
In an Android system, the application's resource is stored in the database and can be shared, so the resource gets the URI of the app.
Uri uri = uri.parse ("android.resource://" +getpackagename () + "/" +r.raw.xinyueshenhua); Uri uri = uri.parse ("android.resource://" +getpackagename () + "/" +r.drawable.ic_launcher);
We can also further encapsulate
public static Uri Getresourceuri (int resid,string packagename) {return uri.parse ("android.resource://" +packagename+ "/ "+resid);}
Android use get resource ID and URI for all apps