使用 webview 崩溃播放 Youtube

play Youtube with webview carshes

我正在尝试使用 WebView 在我的应用程序中播放 YouTube 视频。 但是,当我单击 "Play" 时,应用程序崩溃了。

这是我的代码:

public class Youtube extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_video_item);

    WebView videoView = (WebView)findViewById(R.id.videoView);
    TextView tvTitle = (TextView) findViewById(R.id.VideoTitle);

    WebSettings videoViewSettings = videoView.getSettings();
    videoViewSettings.setJavaScriptEnabled(true);
    videoViewSettings.setPluginState(WebSettings.PluginState.ON);
    videoView.setWebChromeClient(new WebChromeClient());

    String youtubeID ="XSzE2LLFluE";

    tvTitle.setText(youtubeID);
    videoView.loadUrl("http://www.youtube.com/embed/" + youtubeID +"?autoplay=1&vq=small");
    }
}

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

<WebView
    android:id="@+id/videoView"
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:layout_below="@+id/VideoTitle"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"/>

<TextView
    android:id="@+id/VideoTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="@string/imgdesc"
    android:layout_marginRight="10dp"/>

</RelativeLayout>

我正在 Android Studio 模拟器上使用 Nexus 5 测试项目。

您必须添加两行代码:

webView.getSettings().setPluginsEnabled(true); webView.getSettings().setJavaScriptEnabled(true);

这将解决问题。试一试再说。

我发现了这个问题。 因为我在没有 Youtube 应用程序崩溃的情况下在 Emulator 上进行了测试。 在安装了 Youtube 应用程序的设备上运行正常。

现在当我点击 'Full screen' 按钮时它崩溃了