Google Cast SDK3 Android 示例应用在低于 5.0 的设备上崩溃

Google Cast SDK3 Android sample app is crashing on device below 5.0

我已经尝试了 Google Cast Android 示例应用程序,并且在低于 5.0 的设备上崩溃。 任何人都知道为什么?下面是我的崩溃日志:

0830 12:38:57.242: E/AndroidRuntime(16269): 原因: java.lang.RuntimeException: com.google.android.gms.internal.zzsb$zza:找不到可接受的模块。本地版本为0,远程版本为0。 0830 12:38:57.242:E/AndroidRuntime(16269):在 com.google.android.gms.internal.zzni.zzbg(来源不明) 0830 12:38:57.242:E/AndroidRuntime(16269):在 com.google.android.gms.internal.zzni.zza(来源不明) 0830 12:38:57.242: E/AndroidRuntime(16269): 在 com.google.android.gms.cast.framework.CastContext. 没有加一

最新的 Cast SDK 发生了变化,导致它与旧版本的 Google Play 服务不兼容(崩溃)。 不幸的是,当使用带有过时 GPS 的最新 Cast SDK(或在模拟器上)时,即使是 Cast 示例应用程序也会崩溃。 该问题已在此处讨论:https://github.com/googlecast/CastVideos-android/issues/12

解决方案是在初始化任何演员组件之前检查 Google 播放服务版本,包括迷你控制器(即你不能只将迷你控制器片段放入你的 xml 布局文件 - 你要么必须动态地给它充气,或者有两个布局文件——一个有你的迷你控制器,一个没有。

检查 GPS 版本的代码:

GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(context);
isGPSAvailable = (resultCode == ConnectionResult.SUCCESS);

如果结果不是 ConnectionResult.SUCCESS,请不要初始化您的 MiniControllerFragment 并且不要访问 CastContext

此外,请记住 不可能 使用 new MiniControllerFragment() 实例化 MiniControllerFragment。你必须从 xml 开始给它充气,否则你会得到 NullPointerException.

有两种充气方式MiniControllerFragment:

  1. 创建单独的 xml 布局文件并在您的 Activity.onCreate:

    中扩充适当的布局文件
    setContentView(isGPSAvailable ? R.layout.activity_main_with_controller : R.layout.activity_main_without_controller);
    
  2. 在您的布局中创建指向 MiniControllerFragmentViewStub 并仅在您有播放服务时对其进行膨胀。

activity布局:

<ViewStub
android:id="@+id/cast_minicontroller"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout="@layout/cast_mini_controller_fragment"
/>

cast_mini_controller_fragment:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/castMiniController"
          class="com.google.android.gms.cast.framework.media.widget.MiniControllerFragment"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:visibility="gone"/>

代码在你的 activity onCreate():

ViewStub miniControllerStub = (ViewStub) findViewById(R.id.cast_minicontroller);
if (isGPSAvailable) {
    miniControllerStub.inflate();
}

我更喜欢 ViewStub 方法,因为它不会重复您的布局。