Allows Youtube autoplay on Cordova's Android app

Preface

Media autoplay such as Youtube and other functions (*) in mobile application development It is turned off to prevent unnecessary communication, not only when developing native apps The same is true when developing a hybrid app using JavaScript + Cordova.

The Cordova Options (https://cordova.apache.org/docs/en/latest/config_ref/index.html) to turn this on exists in iOS but not in Android. However, "Well, can't youtube autoplay only on Android in development using Cordova: cry:" That's not the case, it's in Android's native app settings API By hitting the method setMediaPlaybackRequiresUserGesture (true / false) You can activate it.

Code fix

File to mess with (com / example / hoge is the app name and namespace. Please read as appropriate.)

platforms/android/app/src/main/java/com/example/hoge/MainActivity.java

import android.os.Bundle;
import org.apache.cordova.*;
import android.webkit.WebSettings; //★ Addition
import android.webkit.WebView; //★ Addition

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
        
        //★ Addition
        WebView wv = (WebView) appView.getEngine().getView();
        WebSettings ws = wv.getSettings();
        ws.setMediaPlaybackRequiresUserGesture(false);
    }
}

Serpentine

If you don't want to keep platforms and below under Git control, save the MainActivity.java file in a different location I think it's better to version control it and use Cordova's hook function to move it before building.

config.xml

<platform name="android">
  <hook type="before_build" src="scripts/updateMainActivity.sh" />
  ...

scripts/updateMainActivity.sh

#!/bin/bash

#For example native_If you have MainActivity in codes
cp native_codes/MainActivity.java platforms/android/app/src/main/java/com/example/hoge/MainActivity.java

Recommended Posts

Allows Youtube autoplay on Cordova's Android app
ROS app development on Android
Notes on calling Installer on Android App
I made a calculator app on Android
Android weather app
[2018 Preservation Version] Reverse Engineering Android App (.apk) on Mac
How to play YouTube videos directly on iOS app
[Android] Notes on xml
Android app Spectrum Analyzer
About Android App Components