SoFunction
Updated on 2025-03-11

How to get the current channel when Android multi-channel packaging

As an Android app, publishing multiple distribution platforms is a regular operation. Then, sometimes, due to different users faced by each channel or different platform review standards, different business logics are needed in each channel, which requires differentiated codes to be selected based on the channel usage.

Here is a brief code.

First of all, it is very easy to package it by channel.

Settings in the project

android {
...
productFlavors {
    home_site {
      dimension "money"
      manifestPlaceholders = [UMENG_CHANNEL_VALUE: "home_site"]
    }
    main_store {
      dimension "money"
      manifestPlaceholders = [UMENG_CHANNEL_VALUE: "main_store"]
    }
    other_store {
      dimension "money"
      manifestPlaceholders = [UMENG_CHANNEL_VALUE: "other_store"]
    }
  }
}

The dimension is the dimension, set through the flavorDimensions.

defaultConfig {
    ...
    flavorDimensions "money"
  }

The dimensions are mainly set for convenience of management.

There are three channels in this project

Among them, UMENG_CHANNEL_VALUE can be named at will, but the channel name is required for the Youmeng Statistics Association in the project, so here we use the UMENG naming method.

The next step is to get the current channel name, so that different logic can be set according to different channel packages, such as setting a certain module to hide the version released by some platforms and then displayed on the versions of other platforms.

First, you need to define the information variable in the file.

<application
    android:icon="@mipmap/logo"
    android:label="@string/app_name"
    android:name=".App"
    android:roundIcon="@mipmap/logo"
    android:theme="@style/">
    ...
    <meta-data
      android:name="CHANNEL_NAME"
      android:value="${UMENG_CHANNEL_VALUE}" />
</application>

Then it can be obtained in Application or Activity.

ApplicationInfo applicationInfo = null;
    try {
      applicationInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
      if (applicationInfo == null) {
        return;
      }
      String value = ("CHANNEL_NAME");
      CommonConfig.CHANNEL_NAME=value;
      //Set differentiated codes by channel      ("CHANNEL_NAME:"+value);
      switch (value){
        case "home_site":
          //Logistic 1          break;
        case "main_store":
          //Logistic 2          break;
        case "other_store":
          //Logistic 3          break;
      }
    } catch ( e) {
      ();
    }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.