美文网首页我爱编程
动态加载jar、dex 热更新

动态加载jar、dex 热更新

作者: gadfly_only | 来源:发表于2018-04-13 23:41 被阅读203次

    Android动态加载jar,dex,apk文件

    image.png

    1.程序没给分配sd卡权限

    1. 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);
        }
    }
    

    相关文章

      网友评论

        本文标题:动态加载jar、dex 热更新

        本文链接:https://www.haomeiwen.com/subject/ezhkkftx.html