将 launching activity 替换为 flavors

Replace launching activity with flavors

是否可以替换获取 intent-filter

的 activity
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

通过配置风格?

是的,只需在产品风味的文件夹中添加清单文件即可

The Manifest of the product flavor is merged on top of the Manifest of the main configuration.

更多信息在这里:http://tools.android.com/tech-docs/new-build-system/build-system-concepts

由于 manifest merger.

,有多种方法可以实现此目的

最简单的方法是在清单中使用占位符并在 build.gradle 中定义适当的 class。

例如,在您的清单中:

<activity android:name="${launchActivityName}">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
</activity>

在你的build.gradle中:

productFlavors {
    flavor1 {
        manifestPlaceholders = [ launchActivityName:"com.example.MainActivity"]
    }
}

您还可以为每种口味添加不同的清单文件。

除了@Tanis 的回答,我想补充一些你应该知道的部分。

productFlavors {
    lite {
        dimension "default"
        applicationId "com.foo.bar"
        manifestPlaceholders = [ applicationLabel:"@string/app_name_foo"
                                 , launcherAct: "com.foo.qux.activity.Hello"
                                 , launcherAct2: "com.foo.qux.activity.World"]
    }
    full {
        dimension "default"
        applicationId "com.foo.qux"
        manifestPlaceholders = [ applicationLabel:"@string/app_name_bar"
                                 , launcherAct: ".activity.World"
                                 , launcherAct2: ".activity.Hello"]
    }
}
  1. 如果你的 World.java 存在于 com.foo.qux.activity 文件夹中,那么你应该使用 完整路径 com.foo.qux.activity.World而不是 .activity.World 将其放入 applicationId "com.foo.bar" flavor 中,否则它将自动添加到文件不存在的 com.foo.bar.activity.World 之前。

  2. 不像android:label,你不能在android:name中使用像@string/launcher_class这样的东西,否则你会构建时得到 error: attribute 'android:name' in <activity> tag must be a valid Java class name.

  3. 确保您不会重复 class,例如:

    <activity
        android:name="${launcherAct}"
        android:label="${applicationLabel}">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    </activity>
    <activity
        android:name="${launcherAct2}"
        android:label="${applicationLabel}">
    </activity>
    

不要忘记从 .activity.World 更改为 android:name="${launcherAct2}",否则你最终会 重复 activity(即 AndroidManifest.xml,另一个在manifestPlaceholders).

  1. Unresolved class 红色指示器可以安全地忽略 ,看起来像 Android Studio 错误:

我做了一个错误报告 here