Android uses Gradle multi-channel packaging

Source: Internet
Author: User

Android Development completed. For an open application, we need to publish to a different application market, at the same time we also need to count the number of users in different markets downloads.

(by starting the app to get different values in different markets apk)

The following is a detailed example to illustrate:
1. Add the Meta-data label to the application in Androidmanifest.xml

<applicationandroid:allowbackup="true"android:icon="@drawable/ Ic_launcher "android:label=" @string/app_name ">                <meta-dataandroid:name= "app_channel"android:value="${app_ Channel_value} " />                    <activityandroid: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, change the Build.gradle file, add in Android {}

android {    // 打包渠道List    productFlavors {        wandoujia {            "豌豆荚"]        }        cn360 {            "360"]        }        baidu {            "百度"]        }        tencent {            "应用宝"]        }        sougou {            "搜狗市场"]        }    }}

Or use the flavor name as ${app_channel_value} using the following method:

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

That's it. Run Gradle assemblerelease drink tea to sit and wait.
After that, you will be able to see various channel packages in build/outputs/apk.

The commands available for Assemble are also:

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

Finally, I enclose my mainactivity and build.gradle.

 Packagecom.example.myandroid;Importandroid.app.Activity;ImportAndroid.content.pm.ApplicationInfo;ImportAndroid.content.pm.PackageManager;ImportAndroid.content.pm.PackageManager.NameNotFoundException;ImportAndroid.os.Bundle;ImportAndroid.widget.Toast;/** * Application Portal * * @author shanhy ([email protected]) * @date December 30, 2015 * * 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 (); }/** * Get application below metadata * * @param name * @return * @author SHA Nhy * @date December 30, 2015 * *     PublicStringGetappmetadata(String meta_name) {Try{ApplicationInfo AppInfo = This. Getpackagemanager (). Getapplicationinfo (Getpackagename (), packagemanager.get_meta_data);returnAppInfo.metaData.getString (Meta_name); }Catch(Namenotfoundexception e)        {E.printstacktrace (); }return NULL; }}

The complete Build.gradle script

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 -Buildtoolsversion"23.0.2"Defaultconfig {//Can be manually changed such as some of the following configurations. No need to change whatever code to generate the appropriate apk for the configurationApplicationID"COM.EXAMPLE.MYANDROID.AAA"Minsdkversion8Targetsdkversion +Versioncode $Versionname"2.0.0"       //DEX breakthrough 65535 LimitMultidexenabledtrue       //Default packaging channel (official)Manifestplaceholders = [App_channel_value:"Official"]    }//Packaging channels listProductflavors {myself {manifestplaceholders = [App_channel_value:"Official"]} wandoujia {manifestplaceholders = [App_channel_value:"Pea pod"]} cn360 {manifestplaceholders = [App_channel_value:" the"]} baidu {manifestplaceholders = [App_channel_value:"Baidu"]} tencent {manifestplaceholders = [App_channel_value:"App Bao"]} sougou {manifestplaceholders = [App_channel_value:"Sogou Market"]        }    }//Packaging channels list   //productflavors {   //Myself {}   //Wandoujia {}   //cn360 {}   //Baidu {}   //Tencent {}   //Sougou {}    //}   //batch processing, directly using the name of the flavor as the value of the App_channel_value (also can not use this method, configured in Productflavors)   //productflavors.all {Flavor   //Flavor.manifestplaceholders = [App_channel_value:name]    //}lintoptions {Abortonerrorfalse} 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 the 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 ')    }//Signature informationSigningconfigs {debug{//No Debug Config} release {StoreFilefile("Xxxxx.key") Storepassword"xxxxx"Keyalias"xxxxx"Keypassword"xxxxx"}} buildtypes {//debug ModeDebug {//Display LOG, called in Java code: Buildconfig.log_debug. The As tool can add this field to the Buildconfig.java, assuming that it is also compatible with Eclipse, and that new fields are not recommended, since eclipse generates Buildconfig.java again after clean (the default use of Buildconfig.debug will satisfy the required Do not have special treatment.)           //buildconfigfield "boolean", "Log_debug", "true"Versionnamesuffix"-debug"           //Do not turn on confusionMinifyenabledfalse           //No zip optimization requiredZipalignenabledfalse           //No resource compression requiredShrinkresourcesfalse           //SigningconfigSigningconfig Signingconfigs.debug}//release ModeRelease {//Do not display log           //buildconfigfield "boolean", "Log_debug", "true"MinifyenabledtrueZipalignenabledtrue           //resource compression, removing useless resource filesShrinkresourcestrue           //Confusing file configurationProguardfiles Getdefaultproguardfile (' Proguard-android.txt '),' Proguard-rules.pro '           //Signature information configuration (assuming that Defaultconfig is configured above without specifying Signingconfig)Signingconfig signingconfigs.release Applicationvariants.all {variant-variant.outputs. each{OUTPUT, def outputFile = Output.outputfileif(OutputFile! =NULL&& OutputFile.name.endsWith ('. apk ')) {//output APK name is called myandroid_v1.0.0_2015-12-30_baidu.apkdef fileName ="Myandroid_v${defaultconfig.versionname}_${releasetime ()}_${variant.productflavors[0].name}.apk"Output.outputfile =NewFile (Outputfile.parent, FileName)}}}}}//Declare a method to get the packing timeDef releasetime () {return NewDate ().format("Yyyy-mm-dd", Timezone.gettimezone ("UTC"))}

Android uses Gradle multi-channel packaging

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.