Android动态加载jar/dex

本文介绍如何在Android应用中动态加载外部的jar包和未安装的APK中的类,并通过反射调用其方法。提供了具体的代码示例,包括处理加载过程中可能出现的异常。

http://www.cnblogs.com/over140/archive/2011/11/23/2259367.html

加载jar

boolean bool = new File("/sdcard/test.jar").exists();
		
		DexClassLoader cl = new DexClassLoader(
				"/sdcard/test.jar", this.getCacheDir()
						.getAbsolutePath(), null, this.getClassLoader());
		try {
			Class<?> c  =  cl.loadClass("HelloWorld");
			
			Object obj = c.newInstance();
			
			Method method = c.getMethod("getHelloWord", null);
			
			String s = (String) method.invoke(obj, null);
			
			TextView tv = (TextView)findViewById(R.id.tv);
			
			tv.setText(s);
			
		} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

  

不要忘记:

将jar优化时应该重新成jar(jar->dex->jar),如果如下命令:

      dx --dex --output=test.jar dynamic.jar

加载未安装APK中的类

 

public class MainActivity extends ActionBarActivity {

	@SuppressLint("NewApi")
	@SuppressWarnings("unused")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		boolean bool = new File("/sdcard/test.apk").exists();
		
		DexClassLoader cl = new DexClassLoader(
				"/sdcard/test.apk", this.getCacheDir()
						.getAbsolutePath(), null, this.getClassLoader());
		try {
			Class<?> c  =  cl.loadClass("com.example.testdexclassloaderloadapk.MainActivity");
			
			Object obj = c.newInstance();
			
			Method method = c.getMethod("getHelloWord", null);
			
			String s = (String) method.invoke(obj, null);
			
			TextView tv = (TextView)findViewById(R.id.tv);
			
			tv.setText(s);
			
		} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

  注意:

1.由于是使用反射,无法取得Context,也就是TestBActivity与普通的类毫无区别,没有生命周期。

2.做实验是出现了: Class ref in pre-verified class resolved to unexpected implementation 错误

查看:http://blog.youkuaiyun.com/berber78/article/details/41721877

原因是 两个工程引用了同样的 appcompat_v7 工程

 大神之作  dl 动态加载架构:

https://github.com/singwhatiwanna/dynamic-load-apk

转载于:https://www.cnblogs.com/wjw334/p/4372676.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值