android - react-native-video 在 Android 背景下崩溃

标签 android react-native react-native-video

我正在实现用于音频播放的视频组件:

import React, {Component} from 'react';
import {StyleSheet, View,} from 'react-native';
import Video from 'react-native-video';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
          <Video source={require('./cats.mp3')}
             ref={(ref) => {
                 this.player = ref
         }}
             playInBackground={true}
             playWhenInactive={true}
             onBuffer={this.onBuffer}               
             onEnd={this.onEnd}                      
             onError={this.videoError}               

          />
      </View>
    );
  }
}

在物理设备 (Pixel 2 8.1.0) 上运行此应用并将应用留在后台时,音频播放会在 3-10 分钟后停止并且应用会崩溃。只能通过重新启动应用程序来重新开始播放。 仅当设备未连接电源线时才会出现此问题。当有外部电源时,应用程序会按预期运行。

我从日志中提取了这个:

ActivityManager: Killing 20894:com.videotest/u0a419 (adj 700): excessive cpu 53130 during 300068 dur=1762444 limit=2

Android 好像是因为 cpu 滥用而拒绝了这个应用? 有什么解决方案可以强制操作系统允许此应用程序不间断地运行,就像我们有外部电源时一样?

native 版本:0.57 react-native-video 版本:3.2.1

最佳答案

我刚刚在 react-native-video issues here 上回答了这个问题,我会把它复制到这里。

============================================= ==========

通过遵循 ExoPlayer 常见问题解答的背景音频指南,我已经设法解决了这个问题,至少对于我的用例而言:https://google.github.io/ExoPlayer/faqs.html#how-do-i-keep-audio-playing-when-my-app-is-backgrounded:

How do I keep audio playing when my app is backgrounded?

There are a few steps that you need to take to ensure continued playback of audio when your app is in the background:

  1. You need to have a running foreground service. This prevents the system from killing your process to free up resources.
  2. You need to hold a WifiLock and a WakeLock. These ensure that the system keeps the WiFi radio and CPU awake.

It’s important that you stop the service and release the locks as soon as audio is no longer being played.

为了在 RN 中实现唤醒锁和 wifilock,我添加了这个包:"react-native-wakeful": "^0.1.0"

为了在 RN 中实现前台服务,我添加了这个包:“@voximplant/react-native-foreground-service”:“^1.1.0”

请务必按照这 2 个包的自述文件中所述更新 AndroidManifest.xml。

这个演示库的 App.js 有一个关于如何使用前台服务的清晰示例:https://github.com/voximplant/react-native-foreground-service-demo/blob/master/App.js:

/**
 * Copyright (c) 2011-2019, Zingaya, Inc. All rights reserved.
 *
 * @format
 * @flow
 * @lint-ignore-every XPLATJSCOPYRIGHT1
 */

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button} from 'react-native';
import VIForegroundService from "@voximplant/react-native-foreground-service";

type Props = {};
export default class App extends Component<Props> {

    async startService() {
        if (Platform.OS !== 'android') {
            console.log('Only Android platform is supported');
            return;
        }
        if (Platform.Version >= 26) {
            const channelConfig = {
                id: 'ForegroundServiceChannel',
                name: 'Notification Channel',
                description: 'Notification Channel for Foreground Service',
                enableVibration: false,
                importance: 2
            };
            await VIForegroundService.createNotificationChannel(channelConfig);
        }
        const notificationConfig = {
            id: 3456,
            title: 'Foreground Service',
            text: 'Foreground service is running',
            icon: 'ic_notification',
            priority: 0
        };
        if (Platform.Version >= 26) {
            notificationConfig.channelId = 'ForegroundServiceChannel';
        }
        await VIForegroundService.startService(notificationConfig);
    }

    async stopService() {
        await VIForegroundService.stopService();
    }


    render() {
        return (
            <View style={styles.container}>
                <Button title="Start foreground service" onPress={() => this.startService()}/>
                <View style={styles.space}/>
                <Button title="Stop foreground service" onPress={() => this.stopService()}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    space: {
        flex: 0.1
    }
});

该示例中缺少的一件事是 stopService() 在开始时需要一个守卫:

  async stopService() {
    // Only Android platform is supported
    if (Platform.OS !== 'android') {
      return;
    }

    await VIForegroundService.stopService();
  }

在我的应用中,当用户点击播放/暂停按钮时,我会这样做:

    // play or pause the player, then.....

    if (this.isPaused) {
      // release wakelock, wifilock and stop foreground service
      wakeful.release();
      this.stopService();
    } else {
      // acquire wakelock, wifilock and start foreground service
      wakeful.acquire();
      this.startService();
    }

wakeful.release()/wakeful.acquire() 可以留在 iOS 中,因为在这种情况下它们只是无操作。

如果有人需要任何帮助,请告诉我:)

关于android - react-native-video 在 Android 背景下崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52400385/

相关文章:

android - 在Flutter应用程序中获取图片流错误

java - Android HttpsConnection - 内部服务器错误

javascript - 如何在React Native中进行条件渲染

react-native - react native : How to detect device lock/unlock event?

ios - 如何在 React Native 中从一个文件导出和导入到另一个文件

安卓 : How can i achieve Listview similar to 'today in history' app?

android - 对两个相关字符串数组进行排序

react-native - 在 react-native-video 中播放 youtube 视频

react-native - 如何修复导入错误 : 'requireNativeComponent' from 'react-native-web'

react-native - 如何使用react-native-video播放谷歌驱动器中的视频?