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

前提条件

Google Cast SDK for Android 是 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. 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.3.1'
        }

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

    注意:如果应用中的方法引用数量超过 65K 限制,应用可能无法 编译。在编译应用时,您可以仅指定应用使用的特定 Google Play 服务 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