使用 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. 验证 google() 是否包含在列出的 repositories 中。
    repositories {
        google()
    }
    
  3. 针对最新版本的 play-services,在 dependencies 下添加新的构建规则。例如:
    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:21.4.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