Android動態(tài)加載jar驶沼,dex桩撮,apk文件
坑
1.程序沒給分配sd卡權(quán)限
- mContext.getClassLoader()
public interface ITest {
public void getWebUrl(String webUrl,OnGetDownLoadUrlListener listener);
}
public interface OnGetDownLoadUrlListener {
void onSuccess(String downUrl);
void onFailed(String error);
}
package com.example.apk;
import android.annotation.SuppressLint;
import android.content.Context;
import java.io.File;
import java.lang.reflect.Constructor;
import dalvik.system.DexClassLoader;
/**
* @author:LiJiaZhi on 2018/4/13
* @des:ToDo
* @org mtime.com
*/
public class Test implements ITest {
private ITest mTest;
private Context mContext;
private String mJarPath;
private String mClassName;
public Test(Context context) {
mContext = context;
getTestInstanceDynamicFromSDCard();
}
/**
* 一定要注意必須有sd卡權(quán)限敦第,不然一直報錯峰弹,class not found
*/
@SuppressLint("NewApi")
private void getTestInstanceDynamicFromSDCard() {
// get test instance by dynamic
mJarPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/loader.dex";// 前半部分為獲得SD卡的目錄
mClassName = "com.example.apk.out.DemoTest";//和導(dǎo)出之前的包名和類名保持一致
File dexOutputDir = mContext.getApplicationContext().getDir("dex", 0);//
File file = new File(mJarPath);
DexClassLoader classLoader = new DexClassLoader(file.getAbsolutePath(),
dexOutputDir.getAbsolutePath(), null, mContext.getClassLoader());
try {
Class<?> clazz = classLoader.loadClass(mClassName);
Constructor<?> constructor = clazz.getConstructor(new Class[]{});//得到構(gòu)造器
mTest = (ITest) constructor.newInstance();//實例化
//or這種方法
//Class clazz = classLoader.loadClass(mClassName);
//mTest = (ITest) clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void getWebUrl(String webUrl, OnGetDownLoadUrlListener listener) {
mTest.getWebUrl(webUrl,listener);
}
}