使用 Cast 应用框架 (CAF) 进行 Android 开发的相关设置

前提条件

Android 版 Google Cast SDK 是 Google Play 服务 SDK 的一部分,无需单独下载。

注意:借助 Google Play 服务,您可以访问一系列 API,用于构建广告、收集分析数据、验证用户身份、集成地图等。如需了解详情,请参阅 Google Play 服务概览。 您务必要确保用户设备上安装了正确的 Google Play 服务 APK,因为更新可能不会立即面向所有用户推出。

将 Google Play 服务添加到您的项目中

在下方选择您的开发环境,然后按照提供的步骤将 Google Play 服务添加到您的项目中。

Android Studio

如需让您的应用可以使用 Google Play 服务 API,请执行以下操作:

  1. 打开应用模块目录中的 build.gradle 文件。

    注意:Android Studio 项目包含一个顶级 build.gradle 文件,以及每个模块的 build.gradle 文件。请务必修改应用模块的文件。如需详细了解 Gradle,请参阅 使用 Gradle 构建项目

  2. 验证所列出的 repositories 中是否包含 google()
    repositories {
        google()
    }
  3. dependencies 下为最新版本的 play-services 添加新的 build 规则。例如:
    apply plugin: 'com.android.application'
        ...
    
        dependencies {
            implementation 'androidx.appcompat:appcompat:1.3.1'
            implementation 'androidx.mediarouter:mediarouter:1.2.5'
            implementation 'com.google.android.gms:play-services-cast-framework:22.1.0'
        }

    请务必在每次更新 Google Play 服务时更新此版本号。

    注意:如果应用中的方法引用数量超过65K 限制,应用可能无法编译。在编译应用时,您可以只指定应用使用的特定 Google Play 服务 API,而不是所有 API,从而缓解此问题。如需了解如何执行此操作,请参阅将 API 有选择地编译到可执行文件中

  4. 保存更改,然后点击工具栏中的 Sync Project with Gradle Files

其他 IDE

如需让您的应用可以使用 Google Play 服务 API,请执行以下操作:

  1. 将库项目从 <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/ 复制到您维护 Android 应用项目的位置。
  2. 在您的应用项目中,引用 Google Play 服务库项目。如需详细了解如何执行此操作,请参阅 在命令行中引用库项目

    注意:您应引用已复制到开发工作区的库副本,而不应直接从 Android SDK 目录引用该库。

  3. 将 Google Play 服务库添加为应用项目的依赖项后,打开应用的清单文件,然后将以下标记添加为 <application> 元素的子元素:
    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

将项目设置为引用库项目后,您就可以开始使用 Google Play 服务 API 开发功能了。

创建 Proguard 例外

为防止 ProGuard 剥离必需的类,请在 /proguard-project.txt 文件中添加以下行:

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames class * implements android.os.Parcelable
-keepclassmembers class * implements android.os.Parcelable {
  public static final *** CREATOR;
}

-keep @interface android.support.annotation.Keep
-keep @android.support.annotation.Keep class *
-keepclasseswithmembers class * {
  @android.support.annotation.Keep <fields>;
}
-keepclasseswithmembers class * {
  @android.support.annotation.Keep <methods>;
}

-keep @interface com.google.android.gms.common.annotation.KeepName
-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
  @com.google.android.gms.common.annotation.KeepName *;
}

-keep @interface com.google.android.gms.common.util.DynamiteApi
-keep public @com.google.android.gms.common.util.DynamiteApi class * {
  public <fields>;
  public <methods>;
}

-dontwarn android.security.NetworkSecurityPolicy