Android外掛程式化開發之DexClassLoader動態載入dex、jar小Demo

來源:互聯網
上載者:User

標籤:catch   ref   pre   com   tostring   類載入   目錄   --   ack   

一、溫故動態載入ClassLoader機制

如果對Android的ClassLoader載入機制不熟悉,猛戳Android外掛程式化開發動態載入基礎之ClassLoader工作機制 http://blog.csdn.net/u011068702/article/details/53248960

二、介紹         我們知道在Android中可以跟java一樣實現動態載入jar,但是Android使用德海Dalvik VM,不能直接載入java打包jar的byte code,需要通過dx工具來最佳化Dalvik bytecode。
         Android在API中給出可動態載入的有:DexClassLoader 和 PathClassLoader(上面串連已經詳細介紹)
         DexClassLoader:可載入jar、apk和dex,可以從SD卡中載入(這篇部落格採用這種方式)

         PathClassLoader:只能載入已經安裝搭配Android系統中的apk檔案

三、曝Demo照片,不要怕,不多,很簡單

四、編寫介面檔案
package com.example.testclassloader;public interface ShowString {public String sayChenyu();}

五、編寫介面實現檔案
package com.example.testclassloader;import android.util.Log;public class ShowStringClass implements ShowString{public static final String TAG = "ShowStringClass";@Overridepublic String sayChenyu() {String chenyu = "chenyu";Log.i(TAG, chenyu);return chenyu;}}

六、打包成jar檔案編譯成dex我們把ShowStringClass.java檔案打包產生showStringClass.jar檔案,然後把檔案放到sdk目錄下的build-tools下的23.0.1目錄下,我用的是ubuntu,所以會看到dex檔案,如果是window會在這個目錄下看到dex.bat檔案,然後用下面命令把showStringClass.jar產生showStringClass_imle.jar的dex檔案
dx --dex --output=showStringClass_impl.jar showStringClass.jar
然後再把showStringClass_impl.jar檔案放到手機目錄裡面去用這個命令
adb push showStringClass_impl.jar  /sdcard/
具體操作圖片如下

七、然後編寫MainActivity.java檔案
package com.example.testclassloader;import java.io.File;import android.content.Context;import android.os.Bundle;import android.os.Environment;import android.support.v7.app.ActionBarActivity;import android.util.Log;import android.widget.TextView;import dalvik.system.DexClassLoader;public class MainActivity extends ActionBarActivity {    public static final String TAG = "MainActivityClassLoader";    public static final String SHOWSTRINGCLASS = "showStringClass_impl.jar";    public static final String SHOWSTRINGCLASS_PATH= "com.example.testclassloader.ShowStringClass";    public static final String DEX = "dex";    public ShowStringClass mShowStringClass = null;    public TextView mTv =  null;    public int i = 0;    @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mTv = (TextView)findViewById(R.id.hello);DexClassLoader(this);}/** * 使用DexClassLoader方式載入類 */public void  DexClassLoader(Context context) {// dex壓縮檔的路徑(可以是apk,jar,zip格式)        String dexPath = Environment.getExternalStorageDirectory().toString() + File.separator + SHOWSTRINGCLASS;        // dex解壓釋放後的目錄        String dexOutputDirs = Environment.getExternalStorageDirectory().toString();        //指定dexoutputpath為APP自己的緩衝目錄        File dexOutputDir = context.getDir(DEX, 0);               // 定義DexClassLoader        // 第一個參數:是dex壓縮檔的路徑        // 第二個參數:是dex解壓縮後存放的目錄        // 第三個參數:是C/C++依賴的本地庫檔案目錄,可以為null        // 第四個參數:是上一級的類載入器        //DexClassLoader dexClassLoader = new DexClassLoader(dexPath,dexOutputDirs,null,getClassLoader());        DexClassLoader dexClassLoader = new DexClassLoader(dexPath,dexOutputDir.getAbsolutePath(),null,getClassLoader());        Class libProvierClazz = null;        // 使用DexClassLoader載入類        try {            libProvierClazz = dexClassLoader.loadClass(SHOWSTRINGCLASS_PATH);            // 建立dynamic執行個體            mShowStringClass = (ShowStringClass) libProvierClazz.newInstance();            if (mShowStringClass != null) {            final String chenyu = mShowStringClass.sayChenyu();            if (chenyu != null) {            mTv.post(new Runnable() {@Overridepublic void run() {mTv.setText(chenyu);}            });            }            } else {            Log.d(TAG, "mShowStringClass is null");            }        } catch (Exception e) {            e.printStackTrace();        }}/** * 列印系統的classLoader */public void showClassLoader() {ClassLoader classLoader = getClassLoader();        if (classLoader != null){            Log.i(TAG, "[onCreate] classLoader " + i + " : " + classLoader.toString());            while (classLoader.getParent()!=null){                classLoader = classLoader.getParent();                Log.i(TAG,"[onCreate] classLoader " + i + " : " + classLoader.toString());                i++;            }        }}}

八、運行Demo的結果爆照在ubuntu終端列印結果如下
手機上面照片如下
說明載入外部的檔案載入成功了
如果把上面那行代碼改成這個
DexClassLoader dexClassLoader = new DexClassLoader(dexPath,dexOutputDirs,null,getClassLoader());
會報下面的錯誤
需要加上緩衝Dex檔案的目錄
      //指定dexoutputpath為APP自己的緩衝目錄        File dexOutputDir = context.getDir(DEX, 0);

九、總結1、加深動態載入的理解2、如何?項目載入外部的Dex檔案有了更好的理解3、對DexClassLoader 、dexClassLoader.load(package.class)、 class.newInstance() 有了更好的理解

Android外掛程式化開發之DexClassLoader動態載入dex、jar小Demo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.