当前位置:操作系统 > 安卓/Android >>

dex文件手动加载

 将已经编译好的.class或者.dex文件放在sdcard中,供一个已安装的程序动态调用:

首先将.class文件转换成.dex文件:

package com.dynamic;
public inte易做图ce IDynamic {
public String helloWorld();
}

 

 

package com.dynamic;
public class DynamicTest implements IDynamic {
    @Override
    public String helloWorld() {
        return "Hello World!";
    }
}

将com.dynamic打包成dynamic.jar

 


将jar包dynamic.jar放到D:\soft\sdk\sdk\platform-tools目录下,dos命令切换到此目录下,输入dx --dex --output=dynamic.dex dynamic.jar,将此目录下生成的dynamic.dex文件放到sdcard里面。


[java]
final File optimizedDexOutputPath = new File(Environment.getExternalStorageDirectory().toString()+File.separator +"wftech"+ 
                File.separator+"dex"+File.separator+ "dynamic.dex");//将dynamic.dex放到/mnt/wftech目录下  
                DexClassLoader cl = new DexClassLoader(optimizedDexOutputPath.getAbsolutePath(), 
                        <STRONG><SPAN style="COLOR: #ff0000">MainActivity.this.getDir("dex", 0).getAbsolutePath()</SPAN></STRONG>,//一定不能写错  
                    null, getClassLoader()); 
                Class libProviderClazz = null; 
                try { 
                    libProviderClazz = cl.loadClass("com.dynamic.DynamicTest"); 
                    IDynamic lib = (IDynamic)libProviderClazz.newInstance(); 
                    Toast.makeText(MainActivity.this, lib.helloWorld(), Toast.LENGTH_SHORT).show(); 
                } catch (Exception exception) { 
                    exception.printStackTrace(); 
                } 

final File optimizedDexOutputPath = new File(Environment.getExternalStorageDirectory().toString()+File.separator +"wftech"+
             File.separator+"dex"+File.separator+ "dynamic.dex");//将dynamic.dex放到/mnt/wftech目录下
             DexClassLoader cl = new DexClassLoader(optimizedDexOutputPath.getAbsolutePath(),
               MainActivity.this.getDir("dex", 0).getAbsolutePath(),//一定不能写错
     null, getClassLoader());
                Class libProviderClazz = null;
                try {
                 libProviderClazz = cl.loadClass("com.dynamic.DynamicTest");
                 IDynamic lib = (IDynamic)libProviderClazz.newInstance();
                 Toast.makeText(MainActivity.this, lib.helloWorld(), Toast.LENGTH_SHORT).show();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }

 

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,