在flutter中杀死应用程序后在后台播放音乐

问题描述 投票:0回答:2

如何实现这个功能?即使在杀死应用程序后,我也需要在后台播放音乐,或者我们可以在从最近使用中删除该应用程序后。

我尝试根据视频更改主文件

import 'package:just_audio_background/just_audio_background.dart';
import 'package:flutter/material.dart';
import 'Home.dart';

Future<void> main() async {
  await JustAudioBackground.init(
    androidNotificationChannelId: 'com.ryanheise.bg_demo.channel.audio',
    androidNotificationChannelName: 'Audio playback',
    androidNotificationOngoing: true,
  );
  runApp(Home());
}
flutter dart flutter-dependencies
2个回答
0
投票
  1. 删除audioplayer.dispose()(无论已实现的地方)。
  2. 查看 didChangeAppLifecycleState 实现,它允许您控制应用程序处于非活动、暂停、恢复状态

0
投票

将 MaterialApp 放入

StatefulWidget
中并在其上放置以下代码

 @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      if (AppLifecycleState.detached == state) {
        player.stop();
      }
    });
  }

OR

将下面的代码放在MaterialApp所在的父类

StatefulWidget

 @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      if (AppLifecycleState.detached == state) {
        player.stop();
      }
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.