Android app plug-in development solution [go]

Source: Internet
Author: User

First, the real demand description

In general, an Android application in the development to a certain stage, the function module will be more and more, the APK installation package is also growing, users in the use of the process there is no way to selectively load their own required function modules. You might want to consider how to split the entire application at this point.

Second, the solution proposed

Generally there are two ways, one is to split the application into multiple applications according to function, which users need to download which, all need to download. Between applications, you can make certain connections at the code level to share part of the information. Another way, similar to other platform plug-in way, the user can be in the main application can selectively download the required plug-in, do not need this feature, you do not need to download.

In the first way, it's enough to develop multiple applications. The second approach is slightly more complex and requires a lot of extra work. Here we briefly discuss the approximate implementation of the second method.

Iii. Overview of the implementation methods

One might think that if you could download a DLL-like file or a jar package like any other platform, it would automatically recognize and load the feature? Unfortunately, the Android platform is not allowed to directly load the jar package, the author did not think of a similar approach. So, to do this, you still have to load it in a standalone apk. And the first way is different, from the design point of view, the specific plug-in is not independent operation of the portal, also does not allow the presence of desktop icons, must be opened from the main application, closed back to the main application (since the plugin is the APK, it installed after the installation of the entrance? How can there be no desktop icon? QQ Parkour and other games is not a plugin? No, there's an icon entry? )。 From a user's point of view, you can load the required functionality and use it in your app, which is similar to the way other platform plugins are.

In order to implement this approach, from a design perspective, it is necessary to consider which features are available to the user as standalone plugins, which are no longer detailed here. The following is an overview of the work that needs to be done from a development perspective.

Ø framework features that need to be developed in the main application:

Identify if the specific plugin is already installed (based on the plugin's package name)

If you have installed to determine if you need to upgrade (server-side to get the latest version and local comparison)

Download and install (or upgrade) the plugin

Uninstall the Plugin

Ø plug-in APK development needs to note:

Do not provide a boot entry in the manifest file

Ø tips for interacting between the main app and plug-ins:

The best use of the same android:shareduserid, plug-ins can easily get the main application of resources, databases and so on.

The main application can start the specific plug-in in intent mode, bring in the map type parameter or JSON string parameter, parse the specific parameters in the plugin apk, realize the business logic.

Iii. Other Notes

This blog content does not specify how to implement, there is no code-level instructions. But in the way described above, developers can basically understand how to implement plug-in Android applications. Specific, in the development process may also encounter a lot of problems, developers need to explore and improve their own.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////

The framework has been released:

Android-application-plug-ins-frame-work android Application plug-in development framework--AAP framework

In the development of Android project, we will encounter the real contradiction between the late function expansion and the main program code change, which is the flexibility of the program.

Due to the security mechanism of Linux platform, coupled with the special mechanism of Dalvik, various authority barriers, it makes it more difficult to develop a flexible and changeable program, which is not as easy as PC platform.

Look at the Elipse plug-in, look at the plug-in 360, under Android, we have a difficult time to write a main program, and then through the plug-in mechanism to deal with the future function expansion, so the program becomes less flexible and changeable.

For example, an Android security software, the new version added a feature, such as SMS interception, often because of a module of the increase, and recompile an APK package, so the cycle, even if only add 50kb of function code, users also need to upgrade a full apk, often 5~6m volume.

Recently reasoning, think of a method, since Tencent QQ under Android can be in the form of apk to change the skin, this resource file expansion can be so easy to engage in, why the expansion of the function can not?

Think of two solutions.

First of all.

Demo download at the end

First, the analysis of ideas.

Under Android, the default is that each apk is independent of each other, basically each application is a Dalvik virtual machine, there is a UID, and then with the Linux itself permissions mechanism, so that apk interoperability is difficult to directly. But as a standalone application of integration, no matter how many apk, can and for a separate Dalvik virtual machine, the visual reflection to the developer is the shell under the process, those several apk loaded at the same time, a process exists.

This is mainly the project manifest file mainfest configuration, just a word, take my test demo as an example:

..... <manifest xmlns:android= "http://schemas.android.com/apk/res/android"      package= " Org.igeek.plugintest.main "      <!--is this key code--      android:shareduserid=" Org.igeek.plugintest "      Android:versioncode= "1"            android:versionname= "1.0";


In the above code, Android:shareduserid refers to a common UID, that is, all this property is the same project, will share the same UID, so that the authority barrier is eliminated, Dalvik will be fused as a, you can test, write a few works, Without this attribute and having this attribute in the case, running concurrently, in listing the current process, is intuitively illustrated.

Program expansion of the plug-in, of course, the need for a main program, the main program is to implement basic functions, as well as the UI, as well as plug-in retrieval and plug-in calls.

The main activity code in my demo is posted here:

  1 public class Andoirdpluginactivity extends Activitygroup implements Onclicklistener, onscrollcompletelistener{2  Private LinearLayout llmainlayout;  3 4//workspace, see Luncher Source, this is the desktop that multi-screen implementation of 5 private workspace wkmain;  6 private Button Btnfindplugins;  7 Private CheckBox Chbattachmain; 8 9 private Localactivitymanager M_activitymanager; 10 11//The collection of this bean is equivalent to the description of the plug-in collection 12//Each Bean is also a plugin of various descriptions of the private list<pluginbean> plugins; @Override-public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstances Tate); Setcontentview (R.layout.main); llmainlayout= (LinearLayout) Findviewbyid (r.id.main_llmainlayout); Wkmain= (WorkSpace) Findviewbyid (R.id.main_wkmain); Btnfindplugins= (Button) Findviewbyid (r.id.main_btnfindplugins); Chbattachmain= (CheckBox) Findviewbyid (R.id.main_chbattachmain); M_activitymAnager = Getlocalactivitymanager (); Wkmain.setonscrollcompletelinstenner (this); Btnfindplugins.setonclicklistener (this); To @Override the public void OnClick (View v) {attachplugin (Findplugins ()); BTNF Indplugins.setvisibility (View.gone); 35} 36 37/** 38 * Load Plug-in list * @param plugins * * * Attachplugin (Final list&lt ; Pluginbean> plugins) {log.e ("Ydt", ""); LOG.E ("Ydt", "-----list plugins"); This.plugins=plugins; (Final Pluginbean plugin:plugins) {btn=new button (this); Btn.settextcol or (color.red); Btn.settext (Plugin.getlabel ()); Llmainlayout.addview (BTN);                 51//Add Event Btn.setonclicklistener (new Onclicklistener () {53 54        @Override-public void OnClick (View v) {56             Boolean isattack=chbattachmain.ischecked (); Intent it=new Intent (); It.setaction (Plugin.getpakagename ());                         60 61//is attached as view if (Isattack) {63 Here to steal the lazy, this is the demo plug-in as view attached to the main program of the Pluginbean plugin:plugins {65 6 6 Intent itt=new Intent (); Itt.setaction (Plugin.getpakagename ()); ViewGroup view= (ViewGroup) (M_activitymanager.startactivity ("", ITT)). Getdecorview (); Wkmain.addview (view); 70} 71//One-time attachment is over, then the buttons are deleted, looking at the clean, these are not the focus of Llmai Nlayout.removeallviews (); Chbattachmain.setvisibility (View.gone); Wkmain.settoscreen (0);     75                }else{76//Here, the plug-in form will not be attached to the main program, purely useless demo startactivity (it ); 78} 79} 80}); 81 82} 83} 84 85/** 86 * Find plugin * @return * */LIST&LT;PLU          Ginbean> Findplugins () {list<pluginbean> plugins=new arraylist<pluginbean> (); 92 93 94//Traverse package name to get plug-in Packagemanager Pm=getpackagemanager (); 98 list<packageinfo> Pkgs=pm.getinstalledpackages (PACKAGEMANAGER.GET_UNINSTALLED_PAC Kages);             PackageInfo pkg:p kgs) {100//Package name 101 String packagename=pkg.packagename;102             String shareduserid= pkg.shareduserid;103 104//shareduserid is the development of the contract, so judging whether it is their own people 105 if (! " Org.igeek.plugintest ". Equals (Shareduserid) | |" Org.igeek.plugintest.main ". Equals (PackageName))106 CONTINUE;107 108//Process name 109 String PRCESSNAME=PKG.APPLICATIONINFO.PR OCESSNAME;110 111//label, which is appname a String Label=pm.getapplicationlabel (pkg.appli Cationinfo). toString (); 113 Pluginbean plug=new Pluginbean (); Plug.setlabel (Labe         l); Plug.setpakagename (PackageName); 117 118 Plugins.add (plug); 119}120      121 122 Return plugins;123 124}125 126 127/**128 * Workspace scrolling to that screen will trigger this event 129 * and each screen in WORKSAPCE is a plugin 130 * This event is used to list the app provided by the current screen plug-in, and lets the user call 131 */132 @Override133 public void Onscrollcomp Lete (Final scrollevent e) {134 try {135 Final Context context = Createpackagecontext (Plugins.get (e.cur screen). Getpakagename (), context.context_include_code|          context.context_ignore_security); 136 llmainlayout.removeallviews (); 137   In these lines, the description of the current plug-in is obtained through reflection, as is the case with most framework XML, which simulates the IOC control reversal 138 Class Clazz=context.getclassloader (). LoadClass (PLU Gins.get (E.curscreen). Getpakagename () + ". Pluginapplication "); 139 Object o=clazz.newinstance (); Map<string,list<string>> r= ( Map<string, list<string>>) clazz.getmethod ("Getdesciption"). Invoke (O); 141 list<string> Class             Es=r.get ("classes"); 142 list<string> Methods=r.get ("methods"); 143 144 145 Here, based on the functionality provided by the obtained plug-in, several button displays are generated for us to call 146 for (final String clas:classes) {147 for (final Strin G method:methods) {148 button Btn=new button (this); 149 btn. SetText (clas+ "," +method+ "); 151 152 153//Click to execute the plugin Method 154 Btn.setonclicklistener (new Onclicklistener () {155 156                        @Override157 public void OnClick (View v) {158 try {159 Class C=context.getclassloader (). LoadClass (Plugins.get (e.curscreen). Getpakagename ()+"."                                 +clas); O1=c.newinstance (); 161 162 Note here that the context is actually a handle, where if the form is involved, plugin's handle is actually not possible because it does not have a 163//attachment Form 164 1 65//This Context is plugin, through testing, dialog this kind of unworkable, toast is possible, because 166//toast is attached to the Screen main window 167//c.getmethod (method,context.class). Invoke (O1,context); 168 169//The handle of the main program is passed in this case. C.getme                             Thod (Method,context.class). Invoke (O1,andoirdpluginactivity.this); 171 172                          } catch (Exception e) {173//TODO auto-generated catch block174       E.printstacktrace (); 175} 176}177}); 178         Llmainlayout.addview (BTN); 179}180}181 182 183         } catch (Exception E1) {184//TODO auto-generated catch block185 e1.printstacktrace (); 186 }187 188}189}


Look at the notes, there are two main points.

Plug-in scanning

This scenario is that each plug-in is released as a separate apk, so you can be flexible in the program to know if there is a new plugin, prompting the user to download the installation, the plugin's APK list describes the action as non-luncher,category as default.

The main program listens to Packgemanager installation complete broadcast, then scans the same package name (plugin of course so defined, as long as the Packgemanager can judge whether the plug-in on the line) of the APK, and then listed, let the user choose whether to load.

Plug-in loading and invocation

After acquiring the package, by calling the system's API can get Shareduserid with the main program of the same apk context, that is, handle, get the handle, through this context can get classloader, and then simple, How do I know what functionality this plugin provides?

This can be described in XML, such as the XML is a resource of the plugin apk, just like the framework of spring. The XML describes what classes this plug-in provides, what methods are available, what parameters they need to pass in, and what types are returned. For convenience in my demo, the interface is used, and each plugin has a class that provides the same method to get a map collection to get a description of the plugin.

OK, here you will know what functionality the plugin is loaded with.

In the code posted above, is to iterate through each plug-in, and each plug-in provided by the function of the button to display to the user, click the button to execute the plug-in function, execution, not the activity to turn (so meaningless), Instead, it executes in the context handle of the main program itself, that is, in its own form.

There is a comment in the code, indicating that if the plugin is useful to the context, remember to pass in the context of the main program, so that the form can be attached to the handle, if it is passed the context of the plug-in, it does not have a form instance, it is not possible to attach some forms, no effect.

Here only to provide ideas, time to study, see if you can get a general framework out. There is another way, not through the apk form, will be written later.

Here are some questions to be verified, such as plug-in permissions issues, if the plug-in needs some permissions in the main program is not declared, what will be a situation, can you apply it in real time? This needs expert guidance. Or in the main program to declare the rights can be declared in advance is also good. There is the problem of native layer code, if the plug-in contains the native layer code, what will be a situation, which also needs to be verified.

This is the demo download:

Http://files.cnblogs.com/hangxin1940/android_plugin_program.rar

Original, reprint please specify http://hangxin1940.cnblogs.com

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.