알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

Flutter Android 생명 주기 리턴 받기 본문

Flutter,Dart

Flutter Android 생명 주기 리턴 받기

백곳 2020. 5. 26. 08:58

한번식 필요할때가 있어 자료를 게시합니다,

 

출처: https://flutter-ko.dev/docs/get-started/flutter-for/android-devs

 

안드로이드 액티비티의 생명주기 이벤트를 어떻게 수신할 수 있나요?

안드로이드에서는 액티비티에 있는 메서드를 오버라이드하여, 액티비티 자체에 있는 생명주기를 메서드를 수정하거나 Application에 ActivityLifecycleCallbacks를 등록할 수 있습니다. Flutter에서는 위와 같은 개념은 없지만, 대신 WidgetsBinding 옵저버에 연결하고 didChangeAppLifecycleState() 변경 이벤트를 수신하여 생명주기 이벤트를 수신할 수 있습니다.

관찰 가능한 생명주기 이벤트는 다음과 같습니다:

  • inactive — 앱이 비활성화 상태이고 사용자의 입력을 받지 않습니다. 안드로이드에서 동일한 이벤트가 없기 때문에 이 이벤트는 iOS에서만 동작합니다.
  • paused — 앱이 현재 사용자에게 보이지 않고, 사용자의 입력을 받지 않으며, 백그라운드에서 동작 중입니다. 안드로이드의 onPause()와 동일합니다.
  • resumed — 앱이 보이고 있고 사용자 입력을 받고 있습니다. 안드로이드의 onPostResume()와 동일합니다.
  • suspending — 앱이 일시 중지 되었습니다. 안드로이드에서 onStop과 동일합니다. iOS에서는 동일한 이벤트가 없기 때문에 호출되지 않습니다.

이 상태들의 의미에 대해 자세한 정보를 알고 싶으시다면, AppLifecycleStatus 문서를 참조하세요.

눈치채셨겠지만, 아주 소수의 액티비티 생명주기만 이용가능합니다; FlutterActivity가 내부적으로 거의 모든 액티비티 생명주기를 캡처하여 Flutter 앤진으로 보내기는 하지만, 대부분은 보호되어 있습니다. Flutter가 엔진을 시작하고 중지하는 일을 처리하고, 대부분의 경우 Flutter 측의 액티비티 생명주기를 관찰할 이유는 거의 없습니다. 네이티브 리소스를 얻거나 배포하기 위해 생명주기를 관찰할 필요가 있다면, 어찌됐든 네이티브 쪽에서 수행해야 할 것입니다. 아래에 포함된 액티비티의 생명주기 상태를 관찰하는 방법의 예시가 있습니다:

 

import 'package:flutter/widgets.dart';

class LifecycleWatcher extends StatefulWidget {
  @override
  _LifecycleWatcherState createState() => _LifecycleWatcherState();
}

class _LifecycleWatcherState extends State<LifecycleWatcher> with WidgetsBindingObserver {
  AppLifecycleState _lastLifecycleState;

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

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _lastLifecycleState = state;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_lastLifecycleState == null)
      return Text('This widget has not observed any lifecycle changes.', textDirection: TextDirection.ltr);

    return Text('The most recent lifecycle state this widget observed was: $_lastLifecycleState.',
        textDirection: TextDirection.ltr);
  }
}

void main() {
  runApp(Center(child: LifecycleWatcher()));
}
Comments