概述
多渠道對于android來說是一個比較常見的概念,舉幾個常見的用法:
- 根據不同的渠道使用不同的資源
- 根據不同的渠道使用不同的依賴
- 根據不同的渠道作不同的資料統計
- 根據不同的渠道,游戲app中對應不同的服務區
github地址
本文專案基于筆者自己寫的demo,對其有興趣的讀者可以自行下載:
https://github.com/Double2hao/MultiChannelTest
android studio的多渠道
如果要使用多渠道,僅需要在該專案的build.gradle檔案中增加以下代碼:
android {
flavorDimensions "version"
productFlavors {
oneTest {
}
twoTest {
}
threeTest {
}
}
}
然后可以在android studio左側欄中的 Build Variants 中選擇module的渠道,如下圖:

buildConfig區分不同的渠道
通過buildConfigField可以在BuildConfig中設定不同的引數,然后在代碼中可以通過BuildConfig的引數來區分不同的渠道,
productFlavors {
oneTest {
buildConfigField("String", "TEST_CHANNEL", "\"one\"")
}
twoTest {
buildConfigField("String", "TEST_CHANNEL", "\"two\"")
}
threeTest {
buildConfigField("String", "TEST_CHANNEL", "\"three\"")
}
}
Demo中BuildConfig的代碼如下:
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.example.multichanneltest";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "threeTest";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
// Field from product flavor: threeTest
public static final String TEST_CHANNEL = "three";
}
Demo中BuildConfig的使用代碼如下:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//根據不同的渠道引數來作不同的邏輯
if (TextUtils.equals(BuildConfig.TEST_CHANNEL, "one")) {
} else if (TextUtils.equals(BuildConfig.TEST_CHANNEL, "two")) {
} else if (TextUtils.equals(BuildConfig.TEST_CHANNEL, "three")) {
}
}
}
manifest區分不同的渠道
通過使用manifestPlaceholders,為不同的渠道設定不同的值,
productFlavors {
oneTest {
manifestPlaceholders = [test_app_name: "TestOneApp"]
}
twoTest {
manifestPlaceholders = [test_app_name: "TestTwoApp"]
}
threeTest {
manifestPlaceholders = [test_app_name: "TestThreeApp"]
}
}
Demo中為不同的渠道設定了不同的appName,代碼如下:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="${test_app_name}"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MultiChannelTest">
</application>
設定不同渠道的資源
通過設定sourceSets,可以為不同的渠道設定不同的資源,
如下,Demo中的代碼,在不同的渠道下,使用不同的java資源,
如果在oneTest的渠道下,"src/main/twoTest"與"src/main/threeTest"目錄下的檔案不會參與編譯,
android {
sourceSets {
oneTest {
java {
srcDirs = ["src/main/java", "src/main/oneTest"]
}
}
twoTest {
java {
srcDirs = ["src/main/java", "src/main/twoTest"]
}
}
threeTest {
java {
srcDirs = ["src/main/java", "src/main/threeTest"]
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/275107.html
標籤:AI
下一篇:Java 并發編程_無鎖并發
