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



我的应用程序在播放商店中被拒绝,原因是"确保它不会启用YouTube视频的后台播放"。我使用了基本的Webview组件,并加载了一个youtube页面。播放完youtube电影并返回主页后,youtube影片将继续在后台播放。

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

您可以使用react native:documentation中的AppState

并且仅当应用程序状态为"活动"时才显示网络视图(其中包含您的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 />
      }
    )
  }
}

如果您使用Expo,这是很好的,无需接触任何本地代码。

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

public class MyReactWebViewManager extends SimpleViewManager<WebView> {
private static final String REACT_CLASS = "RCTMyWebView";
....

在其中,我创建了带有以下onHostPause覆盖的MyReactWebView

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();
    }

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

只需将此道具添加到web视图

mediaPlaybackRequiresUserAction={true}

 <WebView
   mediaPlaybackRequiresUserAction={true}
 />

最新更新