Flutterでアプリの復帰やサスペンドを検出して処理を実行する

公開日:2019/12/02 更新日:2019/12/02
Flutterでアプリの復帰やサスペンドを検出して処理を実行するのサムネイル

はじめに

Flutterでアプリが復帰した時やサスペンドした時を検出して任意の処理を実行するための手順をまとめます。

前提と環境

以下の通りです。

  • Flutter 1.9.1
  • Dart 2.5.0

WidgetsBindingObserverについて

ミックスインとしてWidgetsBindingObserverを使うことでアプリのライフサイクル(復帰、サスペンド等)を検出するメソッドであるdidChangeAppLifecycleStateを使用できるようになります。なお、ライフサイクル以外にも、そのアプリが動作するスマートフォンの言語設定の変更やスマートフォンの向き(縦か横か)の変更を検出するメソッドも用意されています。詳細については以下の公式ドキュメントに記載されています。

api.flutter.dev

Interface for classes that register with the Widgets layer binding. When used as a mixin, provides no-op method implementations.

WidgetsBindingObserverでアプリのライフサイクルを検出する

以下のようにWidgetsBindingObserverをミックスインで使います。

class _MyHomePageState extends State with WidgetsBindingObserver {...}

また、initStatedisposeWidgetsBindingObserverの初期化と破棄を記述します。

class _MyHomePageState extends State with WidgetsBindingObserver {

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

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

  
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if(state == AppLifecycleState.resumed){
      // アプリが復帰した(resumed)時に実行したい処理;
    }
  }

  
  Widget build(BuildContext context) {
// 省略

そして上記のようにdidChangeAppLifecycleStateを使用してアプリのライフサイクルがどの状態であるかを検出し、復帰、サスペンド等に合わせて処理を記述することができます。 didChangeAppLifecycleStateは、アプリがバックグランドに移行した直後、フォアグラウンドに移行した直後に実行されます。

上記はアプリが復帰時(resumed)に処理を実行していますが、他にもinactive(非アクティブ、iOSとAndroidで挙動が異なる)、paused(一時停止)、suspending(Androidのみ)を検出できます。 したがって、以下のように各状態に合わせて実行する処理を分岐させることができます。


void didChangeAppLifecycleState(AppLifecycleState state) {
  if(state == AppLifecycleState.inactive){
    print('inactive');
  }else if(state == AppLifecycleState.resumed){
    print('resumed');
  }else if(state == AppLifecycleState.paused){
    print('paused');
  }else if(state == AppLifecycleState.suspending){
    print('suspending');
  }
}

なお、それぞれのライフサイクルの状態はiOSとAndroidで若干異なります。AppLifecycleStateで使用できる値とiOSとAndroidでの挙動の違いの説明は以下の公式ドキュメントに記載されています。

api.flutter.dev

The values below describe notifications from the operating system. Applications should not expect to always receive all possible notifications.

Android実機で確認したところ、アプリを開いている状態でホームボタンを押してホームに戻るとinactivepauseが共に検出され、ホームからアプリに戻るとinactiveresumeの両方が検出されました。 想定しているアプリの使用方法に基づいてそれぞれ実機で確認したほうが良さそうです。

まとめ

Flutterでアプリの復帰、サスペンドなどのライフサイクルを検出して処理を実行する方法をまとめました。iOSとAndroidで挙動が異なると公式ドキュメントに記載されているので、少し注意が必要そうです。

関連記事

開発アプリ

nanolog.app

毎日の小さな出来事をなんでも記録して、ログとして残すためのライフログアプリです。