插件化知識儲備-加載外部dex

轉載請標明出處:【顧林海的博客】


想要了解插件化,首先得知道如何加載外部的dex文件,這裏的插件APK會存放在主APP的assets目錄中,用於模擬服務器下載插件。

第一步:創建主項目和插件項目

先創建我們的主項目,並在項目中創建一個插件依賴庫,取名爲pluginlibrary,主項目依賴pluginlibrary。

主項目創建完畢後,接着創建插件項目,將項目中的app模塊複製到主項目並重命名爲plugin,同時也依賴pluginlibrary。

修改settings.gradle文件,如下:

include ':app',':plugin', ':pluginlibrary'

重新編譯一下。

第二步:編譯插件APK

將pluginlibrary依賴庫編譯成jar包,並放在插件項目plugin的lib目錄下,不是libs目錄,通過compileOnly引用pluginlibrary的jar包,compileOnly只會在編譯時用到相應的jar,打包成APK後不會存在於APK中。

pluginlibrary編譯jar包,在pluginlibrary的build.gradle的配置如下:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 28

    defaultConfig {
        minSdkVersion 17
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

task clearJar(type: Delete){
    delete 'build/outputs/pluginlibray.jar'
}

task makePluginLibraryJar(type: Copy){
    from ('build/intermediates/packaged-classes/release/')
    into ('build/outputs/')
    include ('classes.jar')
    rename ('classes.jar', 'pluginlibrary.jar')
}

makePluginLibraryJar.dependsOn(clearJar,build)

編譯完成後可以從右側的Gradle面板的other分組中找到makePluginLibraryJar命令:

微信圖片_20181009100628.png

雙擊makePluginLibraryJar命令進行編譯,可以看到底部輸出編譯成功:

BUILD SUCCESSFUL in 4s
50 actionable tasks: 2 executed, 48 up-to-date
10:04:10: Task execution finished 'makePluginLibraryJar'.

在pluginlibrary/build/outputs/下看到pluginlibrary.jar:

微信截圖_20181009100901.png

在plugin項目中創建lib文件夾並將pluginlibrary.jar複製到lib目錄下:

plugin項目的build.gradle修改如下:

    compileOnly files("lib/pluginlibrary.jar")

第三步:加載外部dex

在編譯pluginlibrary.jar之前在項目中創建一個接口:

package com.plugin.administrator.pluginlibrary;

public interface IPluginBean {
    void setUserName(String name);
    String getUserName();
}

在插件plugin項目中就創建一個類:

package com.plugin.administrator.myapplication;

import com.plugin.administrator.pluginlibrary.IPluginBean;

public class UserInfo implements IPluginBean {

    private String name="billgu";

    @Override
    public void setUserName(String s) {
        this.name=s;
    }

    @Override
    public String getUserName() {
        return name;
    }
}

編譯插件plugin項目,將生成的apk複製到主項目的assets目錄下。

接下來就是主項目編寫加載外部DEX文件了,需要把assets目錄下的plugin-debug.apk複製到/data/data/files目錄下,這步操作放在Activity的attachBaseContext方法中:

private String apkName = "plugin-debug.apk";    //apk名稱
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
        try {
            extractAssets(newBase, apkName);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    public static void extractAssets(Context context, String sourceName) {
        AssetManager am = context.getAssets();
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = am.open(sourceName);
            File extractFile = context.getFileStreamPath(sourceName);
            fos = new FileOutputStream(extractFile);
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
            }
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeSilently(is);
            closeSilently(fos);
        }

    }

    private static void closeSilently(Closeable closeable) {
        if (closeable == null) {
            return;
        }
        try {
            closeable.close();
        } catch (Throwable e) {
        }
    }

如何從APK中讀取dex文件,需要藉助於DexClassLoader ,聲明如下:

   DexClassLoader (String dexPath,
              String optimizedDirectory,
             String libraryPath, 
              ClassLoader parent)
  • dexPath: 指目標類所在的jar/apk文件路徑, 多個路徑使用 File.pathSeparator分隔, Android裏面默認爲 “:”

  • optimizedDirectory: 解壓出的dex文件的存放路徑,以免被注入攻擊,不可存放在外置存儲。

  • libraryPath :目標類中的C/C++庫存放路徑。

  • parent: 父類裝載器

在onCreate方法中進行初始化DexClassLoader:

     private String mDexPath = null;    //apk文件地址
    private File mFileRelease = null;  //釋放目錄
    private DexClassLoader mClassLoader = null;
    
    private void initDexClassLoader(){
        File extractFile = this.getFileStreamPath(apkName);
        mDexPath = extractFile.getPath();
        mFileRelease = getDir("dex", 0); //0 表示Context.MODE_PRIVATE
        mClassLoader = new DexClassLoader(mDexPath,
                mFileRelease.getAbsolutePath(), null, getClassLoader());
    }

生成插件APK的classLoader後就可以加載插件plugin-debug.apk中的任何類了。

點擊按鈕事件如下:

buttonGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Class mLoadClassBean;
                try {
                    mLoadClassBean = mClassLoader.loadClass("com.plugin.administrator.myapplication.UserInfo");
                    Object beanObject = mLoadClassBean.newInstance();

                    IPluginBean pluginBean= (IPluginBean) beanObject;
                    pluginBean.setUserName("顧林海");
                    Toast.makeText(getApplicationContext(), pluginBean.getUserName(), Toast.LENGTH_LONG).show();

                } catch (Exception e) {

                }
            }
        });

加載插件plugin中的UserInfo類,調用setUserName和getUserName方法,點擊按鈕Toast顯示“顧林海”。至此加載外部dex文件中的類就結束了。

掃碼_搜索聯合傳播樣式-標準色版.png

Android、Java、Python、Go、PHP、IOS、C++、HTML等等技術文章,更有各種書籍推薦和程序員資訊,快來加入我們吧!關注技術共享筆記。

838794-506ddad529df4cd4.webp.jpg

搜索微信“顧林海”公衆號,定期推送優質文章。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章