您的位置:首页 > 移动开发 > Android开发

android APK加固篇-2.动态加载dex及dex的方法的调用

2016-02-02 11:02 573 查看
1.用于动态加载的dex可以放在sdcard中进行加载,但是为了安全起见还是觉得放在asset中,

加载之前把dex复制到app的data空间中更好。

String copyDex(String dexName) {
AssetManager as = getAssets();
String path = getFilesDir() + File.separator + dexName;
Log.i(TAG, path);
try {
FileOutputStream out = new FileOutputStream(path);
InputStream is = as.open(dexName);
int count = is.available();
while (count > 0) {
byte[] buffer = new byte[count > 1024 ? 1024 : count];
int len = is.read(buffer);
out.write(buffer);
count -= len;
}
out.close();

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "";
}
return path;
}

2.使用前面生成的dex文件构造DexClassLoader对象生成优化后的dex文件。

public void loadDex() {
String path = copyDex("test.dex");
if (path.isEmpty())
return;
mDex = new DexClassLoader(path, getCacheDir().toString(), null,
getClassLoader());
}

3.通过DexClassLoader对象加载对应的class,反射调用其中的方法。

public void test() {
try {
Class TestDex = mDex.loadClass("com.example.dextest.Test1");
Constructor localConstructor = TestDex
.getConstructor(new Class[] {});
Object instance = localConstructor.newInstance(new Object[] {});
methodTest = TestDex.getDeclaredMethod("test",
new Class[] { Activity.class });
methodTest.setAccessible(true);
methodTest.invoke(instance, new Object[] { this });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


4.为了防止root手机,文件被恶意注入,最好在拷贝之前删除掉之前拷贝的dex,和生成的优化后的dex。

源码链接:http://download.csdn.net/detail/csdn49532/9425977



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息