Search code examples
flutterandroid-studiodebuggingfirebase-cloud-messaging

How to debug Flutter app that starts from a killed / terminated state , eg receiving an FCM message?


I would like to test FCM messages that are received when the app is in a terminated state. The problem is Android Studio loses connection after I kill the app. How could I connect back to Android Studio debugger on launch?

I found this old thread How to debug app when it's killed but dont know if we have such a function in Flutter?

android.os.Debug.waitForDebugger();

I need to be able to see the logger output on whats happening in the app.


Solution

  • It is not real debugging, but in case of an Android device, you can add print statements to your code where you handle FCM notifications, and run the app from terminal in release mode to test. This does not work with iOS, at least I could not make it work.

    Add for example the following:

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    
    @pragma('vm:entry-point')
    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) {
      print('onBackgroundMessage');
    }
    

    Somewhere after FCM is initalized, use this to get the initial message (the one that was clicked by the user when the app was terminated and caused the app to start):

    final initialMessage =
        await FirebaseMessaging.instance.getInitialMessage();
    if (initialMessage != null) {
      print('initialMessage');
    }
    

    After this connect your phone to your computer, start you application from terminal with:

    flutter run --release
    

    Now you can terminate the app. Note that the session in terminal will be still on.

    Check the following scenarios:

    1. If there is a notification while to app is terminated, you will see "onBackgroundMessage".

    2. If the user clicks on the message while the app is terminated, you will see "initialMessage".