如何获取到app后台事件?

在我的flutter项目里一个页面在播放mp3文件,当app滑至后台时音频还是会继续播放?请问如何能够实现当app后台时暂停播放,打开时继续播放?

阅读 2.6k
1 个回答
import 'package:flutter/material.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  AppLifecycleState _appLifecycleState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    _appLifecycleState = state;
    switch(state) {
      case AppLifecycleState.paused:
        // App进入后台
        // 在这里暂停音频播放
        break;
      case AppLifecycleState.resumed:
        // App进入前台
        // 在这里恢复音频播放
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('App Lifecycle Demo'),
        ),
        body: Center(
          child: Text('Current state: $_appLifecycleState'),
        ),
      ),
    );
  }
}

void main() {
  runApp(MyApp());
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题