如何防止React Native Android Webview在后台运行Youtube?

Tam*_*zer 11 android webview react-native

我的应用程序在Play商店被拒绝,因为"确保它无法启用YouTube视频的后台播放".我使用了基本的Webview组件并加载了一个youtube页面.在播放YouTube视频并返回主页后,youtube电影继续在后台播放.

当应用程序暂停时,如何获得暂停Webview的句柄?

Agu*_*ndo 7

您可以使用react-native:document中的AppState.

仅当应用状态为" 有效 " 时才显示webview(其中包含您的YouTube嵌入)

import React, {Component} from 'react'
import {AppState, WebView} from 'react-native'

class AppStateExample extends Component {

  state = {
      appState: AppState.currentState
  }

  componentDidMount() {
      AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
      AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {        
      this.setState({appState: nextAppState});
  }

  render() {

    return (

      {this.state.appState == 'active' &&
           <WebView />
      }

    )

  }

}
Run Code Online (Sandbox Code Playgroud)

如果您正在使用Expo,这是很好的,无需触摸任何本机代码.


Tam*_*zer 2

好的,所以我最终创建了自己的MyReactWebViewManager

public class MyReactWebViewManager extends SimpleViewManager<WebView> {

private static final String REACT_CLASS = "RCTMyWebView";

....
Run Code Online (Sandbox Code Playgroud)

在其中,我MyReactWebView使用以下 onHostPause 覆盖创建:

private static class MyReactWebView extends WebView implements LifecycleEventListener { 
    ...

    @Override
    public void onHostResume() {
        // do nothing
        Log.i(REACT_CLASS,"onHostResume");
        this.onResume();
    }

    @Override
    public void onHostPause() {
        // do nothing
        Log.i(REACT_CLASS,"onHostPause");
        this.onPause();
    }
Run Code Online (Sandbox Code Playgroud)

希望将来这将由react-native 处理。