YouTube Android Player API を使ってYouTubeを再生したいです。
こちらを参考に作りました。
しかし、実行してみるとViewに「YouTubeプレーヤーの初期化中にエラーが発生しました。」と表示されてしまいます。
Logcatを見ると
「D/NetworkSecurityConfig: No Network Security Config specified, using platform default」
という不穏な文があったため調べてみると、Android9以降ではデフォルトでHTTPS通信になったのがエラーの原因のようです。
Android7の端末では正常にYouTubeが再生できたため上記が原因で間違いないと思います。
そのためこちらを参考にして対処してみたのですが何も変わりませんでした。
MainActivity
kotlin
1class MainActivity : YouTubeBaseActivity(){ 2 3 private val API_KEY = "APIのkey" 4 5 @RequiresApi(Build.VERSION_CODES.O) 6 override fun onCreate(savedInstanceState: Bundle?) { 7 super.onCreate(savedInstanceState) 8 setContentView(R.layout.activity_main) 9 10 val playerView = findViewById<YouTubePlayerView>(R.id.Youtube_view) 11 val listener = object: YouTubePlayer.OnInitializedListener { 12 override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) { 13 player?.loadVideo("動画のID") 14 } 15 16 override fun onInitializationFailure(provider: YouTubePlayer.Provider?, result: YouTubeInitializationResult?) { 17 } 18 } 19 playerView.initialize(API_KEY, listener) 20 } 21}
ActivityMain.xml
xml
1<?xml version="1.0" encoding="utf-8"?> 2<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity"> 8 9 <view 10 android:id="@+id/Youtube_view" 11 class="com.google.android.youtube.player.YouTubePlayerView" 12 android:layout_height="wrap_content" 13 android:layout_width="wrap_content" /> 14 15</RelativeLayout>
network_security_config.xml
xml
1<?xml version="1.0" encoding="utf-8"?> 2<network-security-config> 3 <domain-config cleartextTrafficPermitted="true"> 4 <domain includeSubdomains="true">youtu.be</domain> 5 </domain-config> 6</network-security-config>
AndroidManifest
xml
1<?xml version="1.0" encoding="utf-8"?> 2<manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 package="com..."> 5 <uses-permission android:name="android.permission.INTERNET" /> 6 <application 7 android:allowBackup="true" 8 android:icon="@mipmap/ic_launcher" 9 android:label="@string/app_name" 10 android:roundIcon="@mipmap/ic_launcher_round" 11 android:supportsRtl="true" 12 android:theme="@style/Theme...."> 13 <activity 14 android:name=".MainActivity" 15 android:exported="true" 16 android:networkSecurityConfig="@xml/network_security_config"> 17 <intent-filter> 18 <action android:name="android.intent.action.MAIN" /> 19 <category android:name="android.intent.category.LAUNCHER" /> 20 </intent-filter> 21 </activity> 22 </application> 23 24</manifest>
network_security_config.xmlはちゃんと「res/xml/」に配置してあります。
どうしたらAndroid9以降でYouTubeを再生できるでしょうか?
ご教授よろしくお願いいたします。

回答1件
あなたの回答
tips
プレビュー