Android dynamically loading installed and not installed APK resources

Source: Internet
Author: User

It is useful to dynamically load installed and not installed APK resources in Android development, which can be used to implement skin-changing functions and so on. Today we will study.

First create a new project Plugpicinstall, we need to go to the project's asset directory and drawable directory to copy some of the images that will need to be loaded. Run the project, i.e. install.

Let's take a look at how to implement loading the resources in an already installed APK:

We need to write two methods to get the corresponding ID of the context object and resource for the installed APK, as follows:

/** * This method is used to obtain an installed apk corresponding to the context object * @return * @throws namenotfoundexception */private Context getinstalledcontext () throw S namenotfoundexception {return createpackagecontext ("Com.example.plugpicinstall", context.context_ignore_security | Context.context_include_code);} /** * This method is used to obtain the corresponding resource object in the APK already installed * @param resources * @param restype * @param resname * @return */private int Getresour CeId (Resources resources,string restype,string resname) {return resources.getidentifier (Resname, ResType, " Com.example.plugpicinstall ");}
Next is the code that loads the drawable file to add slices and load strings in the String.xml:

Resources Installedresource = null;try {//Get the Resource object Installedresource = Getinstalledcontext () of the APK already installed. Getresources ();} catch (Namenotfoundexception e) {e.printstacktrace ();} Imageviewinstall.setimagedrawable (Installedresource.getdrawable (Getresourceid (InstalledResource, "drawable", " Three "))); String app_name = installedresource.getstring (Getresourceid (Installedresource, "string", "app_name")); String Hello_world = installedresource.getstring (Getresourceid (Installedresource, "string", "Hello_world")); Toast.maketext (Mainactivity.this, "App_name is:" +app_name+ "===hello_world is:" +hello_world,toast.length_long). Show ();
Here are the resources in asset loaded in the APK that you have installed:

Assetmanager Assetmanager = Getinstalledcontext (). Getresources (). Getassets (); InputStream ins = AssetManager.open (" Six.jpg "); Bitmap Bitmap = bitmapfactory.decodestream (INS); Imageviewinstall.setimagebitmap (BITMAP);
This allows you to load the resource files in the installed apk.


Next, load the files that are not installed in the APK, first uninstall the Plugpicinstall project from your phone, and then copy the APK generated in the bin directory to the corresponding directory in your phone's SD card:

Again, create a new method to get the resource object for the APK that is not installed:

/** * This method is used to get the Reosurces object of the APK not installed * @return */private Resources getuninstalledresource () {//Reflection out Explorer try {class& lt;? > Assetmanager_clazz = Class. forname ("Android.content.res.AssetManager");//Generate Assetmanager Objects Object assetobj = Assetmanager_clazz.newinstance ();//Because the Addassetpath is hidden, it can only be obtained by reflection to get method Addassetmethod = Assetmanager_ Clazz.getdeclaredmethod ("Addassetpath", String.class); Addassetmethod.invoke (Assetobj, "/storage/sdcard0/183/ Plugpicinstall.apk "); Resources resources = Getresources (); Constructor<?>resources_constructor = Resources.class.getConstructor (Assetmanager_clazz, Resources.getdisplaymetrics (). GetClass (), Resources.getconfiguration (). GetClass ()); resources = (resources) Resources_constructor.newinstance (Assetobj,resources.getdisplaymetrics (), resources.getconfiguration ());//Return/ Resources instance of storage/sdcard0/183/plugpicinstall.apk return resources;} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (Instantiationexception e) {e.printstacktrace ();} catch (Illegalaccessexception e) {e.printstacktrace ();} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (  IllegalArgumentException e) {e.printstacktrace ();} catch (InvocationTargetException e) {e.printstacktrace ();} return null;}
The following code implements loading the resources in the APK that is not installed:

String Apkpath = "/storage/sdcard0/183/plugpicinstall.apk"; String Dexpath = MainActivity.this.getDir ("dex", Context.mode_private). GetAbsolutePath ();D Exclassloader ClassLoader = new Dexclassloader (Apkpath, Dexpath, NULL, getClassLoader ()); try {//reflection gets the inner class of the R file drawableclass<?> Drawable_ Clazz = Classloader.loadclass ("com.example.plugpicinstall.r$drawable");//Get All properties of drawable class Field[]fields = Drawable_ Clazz.getdeclaredfields (); for (Field field:fields) {field.setaccessible (True), if (Field.getname (). Equals ("ten")) { <span style= "White-space:pre" ></span>int id = field.getint (new r.id ()); Imageviewinstall.setbackground ( Getuninstalledresource (). getdrawable (ID));}} Reflection gets the internal class of the R file Stringclass<?>string_clazz = Classloader.loadclass ("com.example.plugpicinstall.r$string"); StringBuffer sb = new StringBuffer ();//Get all the properties of the string inner class, which is the string resource of our life in the String.xml file Field[]fields2 = String_ Clazz.getdeclaredfields (); int id = 0;for (Field field:fields2) {//Gets the corresponding string resource id value id = field.getint (new R.ID ()); Sb.append (Getuninstalledresource (). getString (ID));} Toast.maketext (Mainactivity.this,sb.tostring (), Toast.length_short). Show (); catch (ClassNotFoundException e) {e.printstacktrace ();} catch (Illegalaccessexception e) {e.printstacktrace ();} catch ( IllegalArgumentException e) {e.printstacktrace ();}
Again, here's how to get the asset resource without the APK installed:

Assetmanager Assetmanager = Getuninstalledresource (). Getassets (); InputStream ins;try {ins = Assetmanager.open (" Five.jpg "); Bitmap Bitmap = bitmapfactory.decodestream (INS); Imageviewinstall.setimagebitmap (Bitmap);} catch (IOException e) {e.printstacktrace ();}

So far our dynamic load resource has ended.

Review the dynamic loading and create a new class in the Plugpicinstall project Dynamicclass.java as follows:

Package Com.example.plugpicinstall;import Android.app.activity;import Android.widget.toast;public class DynamicClass {private activity mactivity = Null;public void init (activity activity) {this.mactivity = activity;} public void Showhello (String name) {Toast.maketext (mactivity, "Your name is:" +name, Toast.length_short). Show (); public void Showaddresult (int. A,int b) {Toast.maketext (mactivity, "The result is:" + (A+B), Toast.length_short). Show ();}}
The method defined in this class is the one that will need to be loaded and run.

Package the project Plugpicinstall into an apk and put the apk into one of the sdcard directories.


The following is the code that loads the methods in the class Dynamicclass.java class:

To run the Showaddresult method:

String Apkpath = "/storage/sdcard0/183/plugpicinstall.apk"; String Dexpath = MainActivity.this.getDir ("dex", Context.mode_private). GetAbsolutePath ();D Exclassloader ClassLoader = new Dexclassloader (Apkpath, Dexpath, NULL, getClassLoader ()); try {class<?> clazz = Classloader.loadclass (" Com.example.plugpicinstall.DynamicClass "); Object obj = Clazz.newinstance (); Method Initmeghod = Clazz.getdeclaredmethod ("init", Activity.class); Initmeghod.invoke (obj,mainactivity.this);// Use reflection to run the Showaddresult method class[]params = new class[2];p arams[0] = integer.type;params[1] = Integer.type; Method Showaddmethod = Clazz.getdeclaredmethod ("Showaddresult", params); Showaddmethod.invoke (obj, 1,33);} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (Instantiationexception e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace (),} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch ( IllegalArgumentException e) {e.printstacktrace ()} catch (InvocationTargetException e) {E.PRIntstacktrace ();} 
To run the Showhello method:

The storage path of the APK file is string apkpath = "/storage/sdcard0/183/plugpicinstall.apk"; the path to the//dex file is string dexpath = MainActivity.this.getDir ("Dex", Context.mode_private). GetAbsolutePath ();D exclassloader classLoader = new Dexclassloader (Apkpath, Dexpath, NULL, getClassLoader ()); try {//load the required class class<?> clazz = Classloader.loadclass (" Com.example.plugpicinstall.DynamicClass "); Object obj = Clazz.newinstance (); <span style=" White-space:pre "> &LT;/SPAN&GT;//uses reflection to call the Init method, assigning the context object method Initmeghod = Clazz.getdeclaredmethod ("init", activity.class); Initmeghod.invoke (obj,mainactivity.this);//Use reflection to execute the Showhello method, passing in a string parameter, method HelloMethod = Clazz.getdeclaredmethod ("Showhello", String.class); Hellomethod.invoke (obj, "Li Lei");} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (Instantiationexception e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace (),} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch ( IllegalArgumentException e) {e.printstacktrace ();} catch (INvocationtargetexception e) {e.printstacktrace ();} 

Well, this is done by dynamically loading the installed and not installed APK resources.


SOURCE download









Android dynamically loading installed and not installed APK resources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.