Android插件开发机制

插件机制实质上就是由主体程序定义接口,然后由插件去实现这些接口,以达到功能模块化。Android系统是基于Linux内核的,其安全机制也继承了Linux的特性,再加上android framework没有提供插件化编程的接口,使得在android上做插件开发显得很困难。经过与同事的研究和讨论,想到了一种在android上做开发插件的方法。下面直接通过一个demo来说明。

Step1:定义主程序中的接口。

  1. public interface MyInterface {  
  2.     public void test();  
  3. }  
public interface MyInterface {
	public void test();
}
然后将接口打包成.jar包,提供给插件去实现。


Step2:建立插件工程,实现接口。

将Step1中的jar包放到lib文件夹中,并把它加入build path,但千万记得在order and export项不要勾选,即build的时候不把这个jar包build进去,因为在运行时会把这个接口与主程序的接口当做两个不同的类。如下图:

             


实现接口的代码为:

  1. public class PlugAppActivity extends Activity implements MyInterface{  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.main);  
  7.     }  
  8.   
  9.     @Override  
  10.     public void test() {  
  11.     System.out.println(getApplicationInfo().sourceDir);  
  12.     }  
  13. }  
public class PlugAppActivity extends Activity implements MyInterface{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void test() {
	System.out.println(getApplicationInfo().sourceDir);
    }
}

为什么这里要继承Activity呢?这个在下一步说明,这里的Activity可以替代成service、receiver或provider。

在AndroidManifest加入这个Activity(其他组件同理)。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.intsig.plugApp"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" android:sharedUserId="com.main">  
  6.   
  7.     <uses-sdk android:minSdkVersion="7" />  
  8.   
  9.     <application  
  10.         android:icon="@drawable/ic_launcher"  
  11.         android:label="@string/app_name" >  
  12.         <activity  
  13.             android:name=".PlugAppActivity"  
  14.             android:label="@string/app_name" >  
  15.             <intent-filter>  
  16.                 <action android:name="com.intsig.appMain.PLUGIN" />  
  17.                 <category android:name="android.intent.category.DEFAULT" />  
  18.             </intent-filter>  
  19.         </activity>  
  20.     </application>  
  21.   
  22. </manifest>  
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.intsig.plugApp"
    android:versionCode="1"
    android:versionName="1.0" android:sharedUserId="com.main">

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".PlugAppActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.intsig.appMain.PLUGIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这里的sharedUserId是指插件与主程序共用一个Uid,这样就消除了权限的壁垒。Android系统继承了Linux系统管理文件的方法,为每一个应用程序分配一个独立的用户ID和用户组ID,而由这个应用程序创建出来的数据文件就赋予相应的用户以及用户组读写的权限,其余用户则无权对该文件进行读写。例如,如果我们进入到Android系统日历应用程序数据目录com.android.providers.calendar下的databases文件中,会看到一个用来保存日历数据的数据库文件calendar.db,它的权限设置如下所示

  1. root@android:/data/data/com.android.providers.calendar/databases # ls -l    
  2. -rw-rw---- app_17   app_17      33792 2011-11-07 15:50 calendar.db    
root@android:/data/data/com.android.providers.calendar/databases # ls -l  
-rw-rw---- app_17   app_17      33792 2011-11-07 15:50 calendar.db  
这里的app_17就是系统自动分配的Uid。

至于给activity添加的intent-filter中的action也会在后面解释。

Step3:在主程序中获取插件,并调用接口方法。

  1. <SPAN style="FONT-SIZE: 18px">public class MainActivity extends Activity {  
  2.       
  3.     //</SPAN><SPAN style="FONT-SIZE: 12px">预定义的action</SPAN><SPAN style="FONT-SIZE: 18px">  
  4.     public static final String ACTION_PLUGIN = "com.intsig.mainApp.PLUGIN";  
  5.     @Override  
  6.     public void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.main);  
  9.         try {  
  10.             //</SPAN><SPAN style="FONT-SIZE: 12px">查找符合这个action的所有activity即插件,若插件使用的是其他组件换成对应的方法</SPAN><SPAN style="FONT-SIZE: 18px">  
  11.             List<ResolveInfo> infos = getPackageManager().queryIntentActivities(  
  12.                     new Intent(ACTION_PLUGIN), PackageManager.MATCH_DEFAULT_ONLY);  
  13.             ActivityInfo pluginInfo;  
  14.             for(ResolveInfo info:infos){  
  15.             <SPAN style="WHITE-SPACE: pre"> </SPAN>pluginInfo = info.activityInfo;  
  16.                 //</SPAN><SPAN style="FONT-SIZE: 12px">根据插件的安装路径获得ClassLoader</SPAN><SPAN style="FONT-SIZE: 18px">  
  17.                 ClassLoader cl = new PathClassLoader(pluginInfo.applicationInfo.sourceDir,getClassLoader());  
  18.                 //</SPAN><SPAN style="FONT-SIZE: 12px">获得插件类的实例</SPAN><SPAN style="FONT-SIZE: 18px">  
  19.                 MyInterface plugin = (MyInterface) cl.loadClass(pluginInfo.name).newInstance();  
  20.                 plugin.test();  
  21.             }  
  22.         } catch (Exception e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.   
  26.     }  
  27. }</SPAN>  
public class MainActivity extends Activity {
	
	//预定义的action
	public static final String ACTION_PLUGIN = "com.intsig.mainApp.PLUGIN";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
        	//查找符合这个action的所有activity即插件,若插件使用的是其他组件换成对应的方法
        	List<ResolveInfo> infos = getPackageManager().queryIntentActivities(
        			new Intent(ACTION_PLUGIN), PackageManager.MATCH_DEFAULT_ONLY);
        	ActivityInfo pluginInfo;
        	for(ResolveInfo info:infos){
        		pluginInfo = info.activityInfo;
        		//根据插件的安装路径获得ClassLoader
        		ClassLoader cl = new PathClassLoader(pluginInfo.applicationInfo.sourceDir,getClassLoader());
        		//获得插件类的实例
        		MyInterface plugin = (MyInterface) cl.loadClass(pluginInfo.name).newInstance();
        		plugin.test();
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}

    }
}

这里通过intent来找到所有符合条件的activity,即我们之前实现的插件,通过动态的加载类来获得插件实例。主程序的AndroidManifest如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.intsig.mainApp"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" android:sharedUserId="com.main">  
  6.   
  7.     <uses-sdk android:minSdkVersion="7" />  
  8.   
  9.     <application  
  10.         android:icon="@drawable/ic_launcher"  
  11.         android:label="@string/app_name" >  
  12.         <activity  
  13.             android:name=".MainActivity"  
  14.             android:label="@string/app_name" >  
  15.             <intent-filter>  
  16.                 <action android:name="android.intent.action.MAIN" />  
  17.                 <category android:name="android.intent.category.LAUNCHER" />  
  18.             </intent-filter>  
  19.         </activity>  
  20.     </application>  
  21.   
  22. </manifest>  
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.intsig.mainApp"
    android:versionCode="1"
    android:versionName="1.0" android:sharedUserId="com.main">

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

插件中的sharedUserId要与这里的保持一致。

上面三步描述了用android的四大组件来实现插件,但除此之外还有另一种方式。从上面的demo可以发现所有的插件与主程序的sharedUserId都是一致的,那么就可以通过检索所有安装程序的sharedUserId,只要与主程序的一致便可当做是它的插件。在上面的方法中我们获得了插件的路径以及实现接口类的类名,从而能够动态的加载这个类,而通过检索sharedUserId能够获得到路径却无法获得到类名,那么可以在插件中加入一个xml文件来说明插件中包含的实现类,通过读取这个xml来获取出类名和其他一些可能需要的描述信息,这个就会比第一种要复杂一些。总结一下,当插件的功能比较简单,选择第一种方法比较容易实现;当插件功能较多,逻辑复杂时,可以将插件再细分成模块,同时xml文件可以表现出插件的组织结构,那么第二种方法更好一些。


上面所讲的两种方法都是适用于将安装的apk作为插件,实现插件开发还可以通过在sd卡中的指定目录放入插件的jar包或apk文件,原理与上述类似,只是将PathClassLoader换成DexClassLoader,换成它的原因是DexClassLoader的文档描述有一句:“A class loader that loads classes from .jar and .apk files containing a classes.dex entry. This can be used to execute code not installed as part of an application.二者的区别我还没来得及研究,希望有兴趣的同学去研究下。


  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值