Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Studio 基於 Gradle 的多渠道打包完整指南

編輯:關於 Android 程式設計

由於國內 Android 市場渠道眾多,為了統計每個渠道的下載與數據,開發人員往往需要針對每個渠道單獨打包。一個個手動打包顯然太低效,好在 Android Studio 提供了 Gradle,讓這件事變得非常簡單。本文以友盟統計為例,介紹多渠道打包的完整流程。

1. 在 AndroidManifest.xml 中添加渠道標識

<meta-data
    android:name="UMENG_CHANNEL"
    android:value="${UMENG_CHANNEL_VALUE}" />

2. 在 build.gradle 中配置 productFlavors

android {
    productFlavors {
        xiaomi {
            manifestPlaceholders = [UMENG_CHANNEL_VALUE: "xiaomi"]
        }
        baidu {
            manifestPlaceholders = [UMENG_CHANNEL_VALUE: "baidu"]
        }
        wandoujia {
            manifestPlaceholders = [UMENG_CHANNEL_VALUE: "wandoujia"]
        }
    }
}

也可以一次性修改,避免重複:

android {
    productFlavors {
        xiaomi {}
        baidu {}
        wandoujia {}
    }
    productFlavors.all { flavor ->
        flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }
}

3. 寫代碼驗證渠道

public class MainActivity extends AppCompatActivity {
    private TextView mChannel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mChannel = (TextView) findViewById(tv_channel);
        mChannel.setText(getApplicationMetaValue("UMENG_CHANNEL"));
    }

    private String getApplicationMetaValue(String name) {
        String value = "";
        try {
            ApplicationInfo appInfo = getPackageManager()
                    .getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            value = appInfo.metaData.getString(name);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }
}

添加完這段代碼後,點擊右側的 Gradle,就可以看到剛才配置的渠道了:

雙擊 installBaiduDebug,它就會運行並安裝到手機上:

這樣就能獲取到對應的渠道,安裝其他渠道包也會獲取到相應的渠道標識。

4. 打包正式簽名版本

打包正式版本需要先生成 jks 簽名文件,再進行渠道打包:

點擊 Next 來到下一個頁面,就可以選取相應的渠道,也可以一次性選擇全部渠道:

點擊 finish,等待打包完成即可:

安裝後即可驗證渠道是否正確。

5. 自動化打包

以上是手動操作,下面看自動化方式。在 build.gradle 中配置簽名信息:

signingConfigs {
    debug {
        // No debug config
    }
    release {
        storeFile file("../yourapp.keystore")
        storePassword "your password"
        keyAlias "your alias"
        keyPassword "your password"
    }
}

直接把密碼暴露出來並不安全,可以改為從 gradle.properties 讀取:

release {
    storeFile file(RELEASE_STORE_FILE)
    storePassword RELEASE_STORE_PASSWORD
    keyAlias RELEASE_KEY_ALIAS
    keyPassword RELEASE_KEY_PASSWORD
}

然後在 gradle.properties 中加上:

RELEASE_KEY_PASSWORD= "your password"
RELEASE_KEY_ALIAS= "your alias"
RELEASE_STORE_PASSWORD= "your password"
RELEASE_STORE_FILE= "../yourapp.keystore"

接著用 Android Studio 的 Terminal 執行 assemble 命令:

./gradlew assembleDebug   // debug 版本
./gradlew assembleRelease // release 版本

出現 BUILD SUCCESSFUL 即表示成功,此時就能在輸出目錄看到打包好的 apk:

6. assemble 與 Product Flavor 的組合用法

assemble 會和 Build Variants 結合使用,而 Build Variants = Build Type + Product Flavor。舉例說明:

打包 wandoujia 渠道的 release 版本:

./gradlew assembleWandoujiaRelease

只打 wandoujia 渠道(會同時生成 Release 與 Debug):

./gradlew assembleWandoujia

打全部渠道的 Release 版本:

./gradlew assembleRelease

總結 assemble 命令創建 task 的用法:

  • assembleVariant:構建指定 Variant,例如 assembleFlavor1Debug。
  • assembleBuildType:構建指定 Build Type 的所有 APK,例如 assembleDebug 會構建 Flavor1Debug 與 Flavor2Debug。
  • assembleFlavor:構建指定 flavor 的所有 APK,例如 assembleFlavor1 會構建 Flavor1Debug 與 Flavor1Release。

完整的 gradle 配置示例:

apply plugin: 'com.android.application'

def releaseTime() {
    return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
}

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"

    defaultConfig {
        applicationId "com.multi_channel_study.demo"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    def outputFile = output.outputFile
                    if (outputFile != null && outputFile.name.endsWith('.apk')) {
                        // 輸出 apk 名稱如 Multi-Channel_v1.0_2016-11-04_wandoujia.apk
                        def fileName = "Multi-Channel_v${defaultConfig.versionName}_${releaseTime()}_${variant.productFlavors[0].name}.apk"
                        output.outputFile = new File(outputFile.parent, fileName)
                    }
                }
            }
        }
    }

    signingConfigs {
        debug {
            // No debug config
        }
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword RELEASE_STORE_PASSWORD
            keyAlias RELEASE_KEY_ALIAS
            keyPassword RELEASE_KEY_PASSWORD
        }
    }

    productFlavors {
        xiaomi {}
        baidu {}
        wandoujia {}
    }
    productFlavors.all { flavor ->
        flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }
}

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:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
}

這樣就能輕鬆實現多渠道打包了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved