關於AppLifecycleState 檢測應用程序存在的狀態(前後臺監聽)

關於AppLifecycleState檢測應用程序存在的狀態(前後臺監聽)

概念

一個應用程序存在的狀態

下面的值描述來自操作系統的通知

應用程序不應該總是期望收到所有可能的通知

例如,如果用戶從設備中取出電池,在應用程序和操作系統的其他部分突然終止之前,不會發送任何通知

enum AppLifecycleState {
 //應用程序是可見的,並且響應用戶輸入
  resumed,

  /// 應用程序處於非活動狀態,沒有接收用戶輸入
  /// On iOS
  /// 在Android上,這對應於一個應用程序或Flutter主機視圖運行在前臺非活動狀態
  /// 當其他活動被關注時,應用程序會過渡到這種狀態,比如分屏應用程序、電話呼叫、畫中畫應用程序、   /// 系統對話框或另一個窗口
  ///處於這種狀態的應用程序應該假設它們可能在任何時候pause.
  inactive,

  /// 應用程序當前對用戶不可見,不響應用戶輸入,並在後臺運行。當應用程序處於這種狀態時,引擎將不  ///會調用Window.onBeginFrame和Window.onDrawFrame回調。
  paused,

  ///應用程序仍然駐留在Flutter引擎上,但是與任何主機視圖分離。
///當應用程序處於這種狀態時,引擎在沒有視圖的情況下運行。當引擎第一次初始化時,它可以處於 ///attaching a view 的過程中或在由於 Navigator pop,view被銷燬之後。
  detached,
}
void main() {
  // Enable integration testing with the Flutter Driver extension.
  // See https://flutter.io/testing/ for more info.
  runApp(new MyApp());
}

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

class _MyAppState extends State<MyApp>
    with WidgetsBindingObserver{
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("--" + state.toString());
    switch (state) {
    
     
     //切換前臺時,可回調,初始化時,收不到回調
    case AppLifecycleState.resumed:
        break;
        //切換後臺時,inactive,pause先後回調
    case AppLifecycleState.inactive: 
        break;
      case AppLifecycleState.paused: 
        break;
      case AppLifecycleState.detached: 
        break;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
@override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
            title: const Text('前後臺測試')
        ),
        body: Container(
          color: Colors.black,
          child: Text('前後臺測試'),
        ),
      ),
    );
  }
}

參考:Flutter 前後臺切換監聽

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章