Android plug-in development---run the service in the APK that is not installed

Source: Internet
Author: User

If you don't know what plug-in development is, then you should read this blog before: Android plug-in development, first into the palace

The previous blog mainly from the overall point of view of the Android plug-in development of several difficulties and dynamic loading of the APK is not installed in the activity and resource methods. In fact, the general plug-in development is mainly to load an activity, read some resources such as pictures. But there are always special situations, such as loading the service.

To dynamically load the service, there are two ways of thinking: one is to run the service through C + + in the form of the NDK (which I have not tried, just to listen to the friends in the group); In the form of hosting, as the previous blog is not clear, here is a detailed look at the method of loading the service in the plug-in via managed implementations.

The following points are certainly known to every Android development group: An APK is not ready to run if it is not installed. A class file for a Java class can be read by the Classload class loader. An apk is actually a compressed package that contains a. dex file that is our code file. So, the next basic idea we can be clear: the APK is not able to run directly, the APK has code files, code files can be classload read.

There are two kinds of classload in Android, namely Dexclassloader, Pathclassloader. The latter can only load the/data/app directory under the APK that APK must be installed to be loaded, which is not what we want, so we use the former: Dexclassloader.

public class Cjclassloader extends Dexclassloader {//Creates a plug-in loader collection that uses a fixed loader for fixed dex to prevent multiple loaders from loading a single Dex error.     Private static final hashmap<string, cjclassloader> pluginloader = new hashmap<string, cjclassloader> ();        Protected Cjclassloader (String Dexpath, String optimizeddirectory, String LibraryPath, ClassLoader parent) {    Super (Dexpath, Optimizeddirectory, LibraryPath, parent);            }/** * Returns the dexpath corresponding loader */public static Cjclassloader getClassLoader (String dexpath, Context cxt,        ClassLoader parent) {Cjclassloader Cjloader = Pluginloader.get (Dexpath); if (Cjloader = = null) {//Gets the launch path to the app final String Dexoutputpath = cxt. Getdir ("            Dex ", Context.mode_private). GetAbsolutePath ();            Cjloader = new Cjclassloader (Dexpath, Dexoutputpath, NULL, parent);        Pluginloader.put (Dexpath, Cjloader);    } return Cjloader; }}

This is just the beginning, and then we need to consider a problem where a service has a Oncreate->onstart->ondestroy life cycle and some callback methods that are used by the parent class (including the has ..... a ... Relationship) or SDK management, when we load through the ClassLoader, it is not able to manage the parent class, that is to say we need to emulate the SDK to manage the plug-in service callback function. So the class to manage the plug-in service is the one previously mentioned.

Here is an interface that I pulled out of the service callback method to write

Public interface I_cjservice {    ibinder onbind (Intent Intent);     void OnCreate ();     int Onstartcommand (Intent Intent, int flags, int startid);     void OnDestroy ();     void onconfigurationchanged (Configuration newconfig);     void Onlowmemory ();     void ontrimmemory (int level);     Boolean onunbind (Intent Intent);     void Onrebind (Intent Intent);     void ontaskremoved (Intent rootintent);}

A managed class Cjproxyservice extends service{//    adopt the Include relationship    protected i_cjservice mpluginservice;//Plug-in Service object}

Here is a way to include relationships rather than inherit (or implement an interface).

It is because we need to rewrite the methods in the service, and the overridden methods need to use the corresponding interface methods of the interface object.

public class Cjproxyservice extends service{        @Override public    void Onconfigurationchanged (Configuration Newconfig) {        mpluginservice.onconfigurationchanged (newconfig);        Super.onconfigurationchanged (Newconfig);    }     @Override public    void Onlowmemory () {        mpluginservice.onlowmemory ();        Super.onlowmemory ();    }     @Override    @SuppressLint ("Newapi") public    void Ontrimmemory (Int. level) {        mpluginservice.ontrimmemory (level);        Super.ontrimmemory (level);    }     @Override Public    Boolean onunbind (Intent Intent) {        mpluginservice.onunbind (Intent);        return Super.onunbind (intent);    }     @Override public    void Onrebind (Intent Intent) {        mpluginservice.onrebind (Intent);        Super.onrebind (intent);    } }

See here you should also understand that the host is actually a normal service class, but this is the normal operation of the host is the SDK management callback function, we through the service callback function to invoke the plug-in service corresponding callback method, Indirectly manages the life cycle of the plug-in service (here you can compare the relationship between activity and fragment)

So far, we've been able to successfully tune up a plugin service, and the next question is where does this I_cjsrvice object come from? It's simple to load a class loader with a

private void init (Intent itfromapp) {Object instance = null;            try {class<?> serviceclass;            if (CJConfig.DEF_STR.equals (Mdexpath)) {ServiceClass = Super.getclassloader (). LoadClass (MClass);            } else {serviceclass = This.getclassloader (). LoadClass (MClass);            } constructor<?> serviceconstructor = ServiceClass. GetConstructor (New class[] {});        Instance = serviceconstructor.newinstance (new object[] {});        } catch (Exception e) {} setremoteservice (instance);    Mpluginservice.setproxy (this, mdexpath); }/** * keeps a copy of the plug-in service object */protected void Setremoteservice (object service) {if (service instanceof        I_cjservice) {Mpluginservice = (i_cjservice) service;        } else {throw new classcastexception ("plugin service must implements I_cjservice"); }    }

So that you can get a I_cjsrvice object Mpluginservice, if so far, there will be problems, Because at this point in the Mpluginservice, for example, the OnStart method also corresponds to the plug-in OnStart that is the parent class OnStart (here, I do not know how to describe), and before we said that through reflection loaded class is no parent class, Then if the @override method of the reflected object is invoked at this time, the null pointer will be reported because the parent class cannot be found. The solution, then, is to rewrite each @override method in the plugin service.

//....... Limited space, partial interception public abstract class Cjservice extends Service implements I_cjservice {    /**     * That pointer points to the context of the current plug-in (this pointer is absolutely not available due to plug-in development)     *    /protected Service that;//override this pointer     @Override    Public IBinder Onbind (Intent Intent) {        if (Mfrom = = cjconfig.from_plugin) {            return null;        } else {            return T Hat.onbind (intent);}}}    

As you can see by substituting: we use a that object to replace the original this object, and then we just need to assign this object to the managed object by assigning the That is, all the in the plug-in is equivalent to calling the managed, then the purpose of the dynamic replacement is achieved, so we have successfully loaded an unused plugin apk service.

For the code in this class, as well as the full demo, you can focus on: Android Plug-in development framework Cjframeforandroid

Android plug-in development---run the service in the APK that is not installed

Related Article

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: 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.