如题,首先自制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文件夹下
具体调用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String 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