坑
1.程序没给分配sd卡权限
- 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卡权限,不然一直报错,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";//和导出之前的包名和类名保持一致
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[]{});//得到构造器
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);
}
}
网友评论