Android 使用 Gradle 多渠道打包

來源:互聯網
上載者:User

標籤:xxx   roi   instr   append   dex   amp   擷取   alpha   variant   

安卓開發完畢。對於一個開放應用而言,我們須要公布到不同的應用市場,同一時候我們也須要統計不同市場的使用者下載量。

(通過啟動應用後擷取不同市場apk中的不同值來區分)

以下用一個詳細的執行個體來說明:
1、在AndroidManifest.xml的application內加入meta-data標籤

<application    android:allowBackup="true"    android:icon="@drawable/ic_launcher"    android:label="@string/app_name">    <meta-data        android:name="APP_CHANNEL"        android:value="${APP_CHANNEL_VALUE}" />    <activity        android:name=".MainActivity"        android:label="@string/app_name" >        <intent-filter>            <action android:name="android.intent.action.MAIN" />            <category android:name="android.intent.category.LAUNCHER" />        </intent-filter>    </activity></application>

2、改動build.gradle檔案,在android {} 中加入

android {    // 打包渠道List    productFlavors {        wandoujia {            manifestPlaceholders = [APP_CHANNEL_VALUE: "豌豆莢"]        }        cn360 {            manifestPlaceholders = [APP_CHANNEL_VALUE: "360"]        }        baidu {            manifestPlaceholders = [APP_CHANNEL_VALUE: "百度"]        }        tencent {            manifestPlaceholders = [APP_CHANNEL_VALUE: "應用寶"]        }        sougou {            manifestPlaceholders = [APP_CHANNEL_VALUE: "搜狗市場"]        }    }}

或者使用以下方法,直接使用flavor的name做為${APP_CHANNEL_VALUE}

android {    // 打包渠道List    productFlavors {        wandoujia {}        cn360 {}        baidu {}        tencent {}        sougou {}    }    // 批量處理,直接使用flavor的name作為APP_CHANNEL_VALUE的值    productFlavors.all { flavor ->        flavor.manifestPlaceholders = [APP_CHANNEL_VALUE: name]    }}

這樣就完畢了。運行 gradle assembleRelease 喝口茶坐等便可。
完畢後,到build/outputs/apk中就能夠看到各種渠道包。

有關assemble可用的命令還有:

gradle assembleDebug    //全部Debug版本號碼gradle assembleRelease  //全部Release版本號碼gradle assembleBaidu    //指定渠道的Debug和Release版本號碼gradle assembleBaiduDebug   //指定渠道的Debug版本號碼gradle assembleBaiduRelease //指定渠道的Release版本號碼gradle build    //全部渠道的Debug和Release版本號碼

最後附上我的 MainActivity 和 build.gradle

package com.example.myandroid;import android.app.Activity;import android.content.pm.ApplicationInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.os.Bundle;import android.widget.Toast;/** * 應用入口 * * @author SHANHY([email protected]) * @date   2015年12月30日 */public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        String channel = getAppMetaData("APP_CHANNEL");        if(channel != null)            Toast.makeText(this, channel, Toast.LENGTH_SHORT).show();    }    /**     * 擷取Application以下的metaData     *      * @param name     * @return     * @author SHANHY     * @date   2015年12月30日     */    public String getAppMetaData(String meta_name){        try {            ApplicationInfo appInfo = this.getPackageManager()                    .getApplicationInfo(getPackageName(),PackageManager.GET_META_DATA);            return appInfo.metaData.getString(meta_name);        } catch (NameNotFoundException e) {            e.printStackTrace();        }        return null;    }}

完整的 build.gradle 指令碼

buildscript {    repositories {        jcenter()    }    dependencies {        classpath ‘com.android.tools.build:gradle:2.0.0-alpha3‘    }}apply plugin: ‘com.android.application‘dependencies {    compile fileTree(dir: ‘libs‘, include: ‘*.jar‘)}android {    compileSdkVersion 14    buildToolsVersion "23.0.2"    defaultConfig {        // 能夠手動改動例如以下一些配置。無需改動不論什麼代碼便能夠產生相應配置的apk        applicationId "com.example.myandroid.aaa"        minSdkVersion 8        targetSdkVersion 21        versionCode 200        versionName "2.0.0"        // dex突破65535限制        multiDexEnabled true        // 預設打包渠道(官方)        manifestPlaceholders = [APP_CHANNEL_VALUE: "官方"]    }    // 打包渠道List    productFlavors {        myself {            manifestPlaceholders = [APP_CHANNEL_VALUE: "官方"]        }        wandoujia {            manifestPlaceholders = [APP_CHANNEL_VALUE: "豌豆莢"]        }        cn360 {            manifestPlaceholders = [APP_CHANNEL_VALUE: "360"]        }        baidu {            manifestPlaceholders = [APP_CHANNEL_VALUE: "百度"]        }        tencent {            manifestPlaceholders = [APP_CHANNEL_VALUE: "應用寶"]        }        sougou {            manifestPlaceholders = [APP_CHANNEL_VALUE: "搜狗市場"]        }    }    // 打包渠道List    //productFlavors {    //  myself {}    //  wandoujia {}    //  cn360 {}    //  baidu {}    //  tencent {}    //  sougou {}    //}    // 批量處理,直接使用flavor的name作為APP_CHANNEL_VALUE的值(也能夠不使用該方法,在productFlavors中逐一配置)    //productFlavors.all { flavor ->    //  flavor.manifestPlaceholders = [APP_CHANNEL_VALUE: name]    //}    lintOptions {        abortOnError false    }    sourceSets {        main {            manifest.srcFile ‘AndroidManifest.xml‘            java.srcDirs = [‘src‘]            resources.srcDirs = [‘src‘]            aidl.srcDirs = [‘src‘]            renderscript.srcDirs = [‘src‘]            res.srcDirs = [‘res‘]            assets.srcDirs = [‘assets‘]        }        // Move the tests to tests/java, tests/res, etc...        instrumentTest.setRoot(‘tests‘)        // Move the build types to build-types/<type>        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...        // This moves them out of them default location under src/<type>/... which would        // conflict with src/ being used by the main source set.        // Adding new build types or product flavors should be accompanied        // by a similar customization.        debug.setRoot(‘build-types/debug‘)        release.setRoot(‘build-types/release‘)    }    //簽名資訊    signingConfigs {        debug{            // No Debug Config        }        release {            storeFile file("xxxxx.key")            storePassword "xxxxx"            keyAlias "xxxxx"            keyPassword "xxxxx"        }    }    buildTypes {        //Debug模式        debug {            // 顯示LOG,在java代碼中的調用方式為:BuildConfig.LOG_DEBUG。AS工具能夠在BuildConfig.java中新增這個欄位,假設還要相容使用eclipse,不建議使用新增欄位,由於eclipse在clean後會又一次產生BuildConfig.java(預設使用BuildConfig.DEBUG能滿足須要就不要特殊處理了)            //buildConfigField "boolean", "LOG_DEBUG", "true"            versionNameSuffix "-debug"            // 不開啟混淆            minifyEnabled false            // 不須要ZIP最佳化            zipAlignEnabled false            // 不須要資源壓縮            shrinkResources false            // signingConfig             signingConfig signingConfigs.debug        }        //Release模式        release {            // 不顯示LOG            //buildConfigField "boolean", "LOG_DEBUG", "true"            minifyEnabled true            zipAlignEnabled true            // 資源壓縮,移除沒用的資源檔            shrinkResources true            // 混淆檔案配置            proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘            // 簽名資訊配置(假設上面配置了defaultConfig則能夠不用指定signingConfig)            signingConfig signingConfigs.release            applicationVariants.all { variant ->                variant.outputs.each { output ->                    def outputFile = output.outputFile                    if (outputFile != null && outputFile.name.endsWith(‘.apk‘)) {                        // 輸出apk名稱為myandroid_v1.0.0_2015-12-30_baidu.apk                        def fileName = "myandroid_v${defaultConfig.versionName}_${releaseTime()}_${variant.productFlavors[0].name}.apk"                        output.outputFile = new File(outputFile.parent, fileName)                    }                }            }        }    }}// 聲明一個方法,擷取打包時間def releaseTime() {    return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))}

Android 使用 Gradle 多渠道打包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.