完全掌握Android多分包技術MultiDex-用Ant和Gradle分別構建(二)

    在上一篇博客中,我給你們詳細介紹了ant實現Android多分包技術,具體能夠點擊查看:完全掌握Android多分包技術MultiDex-用Ant和Gradle分別構建(一);接下來的這篇博客我將帶領你們一塊兒學習使用Gradle構建Android項目多分包。java

增長多分包配置

    說到Gradle,就不得不提到使用AndroidStudio進行開發,首先看一下在AndroidStudio中咱們整個項目的框架。android

這裏寫圖片描述

    這裏,爲了實現多分包技術,咱們首先須要使用Android SDK Build Tools 21.1及以上的版本,接着修改工程中app目錄下的build.gradle文件,在defaultConfig中添加multiDexEnabled true這個配置項。完成後還須要在dependencies中添加multidex的依賴:bash

compile 'com.android.support:multidex:1.0.0'

具體代碼以下:markdown

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.xingyu.castiel"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

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

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:multidex:1.0.0'

    testCompile 'junit:junit:4.12'
}

代碼中加入multidex功能

方案一:在manifest文件中指定Application爲MultiDexApplication

<application
        android:name="android.support.multidex.MultiDexApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        ……>

方案二:讓應用的Application繼承MultiDexApplication

public class MyApplication extends MultiDexApplication{
……
}

方案三:重寫Application的attachBaseContext方法,該方法放到onCreate前執行

public class MyApplication extends Application{

@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

指定dex文件所包含的類

一般咱們在build.gradle文件中添加afterEvaluate區域,並在其內部採用–main-dex-list選項來指定主dex中要包含的類。app

這裏寫圖片描述

自定義的主包類列表

castielmaindexlist.txt
須要注意的是,multidex的jar包中的9個類必須也要打到主包中,不然程序會由於找不到multidex相關類而拋出異常。框架

// 我主包中包含的類
com/xingyu/castiel/MainActivity.class

// multidex
android/support/multidex/MultiDex.class 
android/support/multidex/MultiDexApplication.class 
android/support/multidex/MultiDexExtractor$1.class 
android/support/multidex/MultiDexExtractor.class 
android/support/multidex/MultiDex$V14.class 
android/support/multidex/MultiDex$V19.class 
android/support/multidex/MultiDex$V4.class 
android/support/multidex/ZipUtil$CentralDirectory.class 
android/support/multidex/ZipUtil.class 

多分包技術可能帶來的問

(1)應用啓動速度會下降
(2)部分android 4.0如下的設備可能會出現兼容問題ide

參考內容:《Android開發藝術探索》學習

相關文章
相關標籤/搜索