自制jar并二次打包,反射调用assets下面的jar

来源:互联网 发布:怎么用excel分析数据 编辑:程序博客网 时间:2024/05/22 13:39

如题,首先自制jar并二次打包,

被打包内容:

package com.example.demo;

import android.content.Context;
import android.widget.Toast;

public class Tools {

    public void Show(Context ctx, String msg){
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }
    
}

打包方法:http://blog.csdn.net/qq_24179679/article/details/52184596

打包完成后,将该jar重命名为xxx.jar(后面代码需要,可以自己定义名字),并复制到项目assets文件夹下


具体调用:

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.button1).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString path = Copy2Files(MainActivity.this);loadJar(MainActivity.this, path);try {if (lclass != null && obj != null) {Method mc = lclass.getMethod("Show",new Class[] {Context.class, String.class});mc.invoke(obj, MainActivity.this, "---xxx---");}} catch (Exception e) {// HdpLog.printException(e);e.printStackTrace();} }});}private Object obj = null;private Class lclass = null;public void loadJar(Context ctx, String path) {if (lclass == null || obj == null) {try {ClassLoader lcl = ClassLoader.getSystemClassLoader();DexClassLoader loader = new DexClassLoader(path, ctx.getDir("dex", 0).getAbsolutePath(), null, lcl);lclass = loader.loadClass("com.example.demo.Tools");Constructor cons = lclass.getConstructor(new Class[] {});obj = cons.newInstance();} catch (Exception e) { e.printStackTrace();}}}public String Copy2Files(Context ctx) {String dexName = "xxx.jar";File dex = new File(ctx.getFilesDir().getAbsolutePath(), "xxx.jar");try {InputStream is = ctx.getResources().getAssets().open(dexName);FileOutputStream fos = null;try {dex.createNewFile();fos = new FileOutputStream(dex);byte[] buffer = new byte[1024];int len = -1;while ((len = is.read(buffer)) != -1) {fos.write(buffer, 0, len);}} catch (Exception e) { e.printStackTrace();} finally {try {if (fos != null) {fos.close();}if (is != null) {is.close();}} catch (IOException e) { e.printStackTrace();}}} catch (Exception e) { e.printStackTrace();}return dex.getAbsolutePath();}
demo地址:http://download.csdn.net/download/qq_24179679/9985816

阅读全文
0 0
原创粉丝点击