WhatsApp like call notification when app in background in flutter

Viewed 1880

On Android, I want to be able to show a persistent notification with two buttons even when the app is in the background or when the phone is locked. Basically, like a WhatsApp incoming call notification.

I know how to do it in Java but I don't know how to do it in Flutter. I've read similar questions on SO but none have provided a good answer.

FYI, I know how to send and receive FCM notifications. I know how to display a normal notification when a FCM message is sent while the app is in the background.

2 Answers

After wasting an entire week, here is the solution I found.

Keep your app running in the background and make sure it is not closed by the user. This tutorial explains how to do it: https://github.com/ppicas/flutter-android-background

If the solution above is too complicated, use the flutter_background to do more or less the same thing (the first solution is better because it also prevents the user from closing the app).

Make sure the flutter activity can be displayed over the lock screen by adding this to your activity's declaration in your manifest:

android:showWhenLocked="true"

Last thing is to use a wakelock in flutter when your app receives a notification, and you want to display a full screen "call received" widget.

You can use firebase_messaging and awesome_notifications

add this in your firebase background subscription handler

await AwesomeNotifications().createNotification(
  content: NotificationContent(
    id: createuniqueId(),
    channelKey: 'basic_channel',
    title: message.data['title'],
    body: message.data['body'],
    wakeUpScreen: true,
    fullScreenIntent: true,
    autoDismissible: false,
    category: NotificationCategory.Call,
    locked: true,
    displayOnForeground: true,
  ),
  actionButtons: [
    NotificationActionButton(
      key: 'accept',
      label: 'Accept',
    ),
    NotificationActionButton(
      isDangerousOption: true,
      key: 'reject',
      label: 'Reject',
    ),
  ],
);

add this is your main()

AwesomeNotifications().initialize(
    'resource://drawable/ic_icon',
    [
      NotificationChannel(
        channelKey: 'basic_channel', 
        channelName: 'Basic Notification', 
        channelDescription: 'Hello world',
        importance: NotificationImportance.High,
        channelShowBadge: true,
        vibrationPattern: highVibrationPattern
      ),
    ]
  );
Related