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