Search code examples
flutterfirebasefirebase-cloud-messaginggoogle-cloud-messaging

FCM Flutter Android Does Not Show Heads Up or Making a Sound When Installed


I'm Trying to use FCM For My App To Send And Receive Notification and it's a major part of my app. the problem I'm facing is when the app (android version) gets installed on (Emulator, Device) it does not show the heads up notification or makes a sound. this my app settings when installed enter image description here and this is my channel. enter image description here

 static Future initFireBase() async {
await Firebase.initializeApp();

NotificationSettings settings = await FirebaseMessaging.instance.requestPermission(
  alert: true,
  announcement: false,
  badge: true,
  carPlay: false,
  criticalAlert: false,
  provisional: false,
  sound: true,
);

if (settings.authorizationStatus == AuthorizationStatus.authorized) {
  print('User granted permission');
} else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
  print('User granted provisional permission');
} else {
  print('User declined or has not accepted permission');
}
FirebaseMessaging.onBackgroundMessage(backgroundHandler);

var token  = await FirebaseMessaging.instance.getToken();
log('Token $token', name: _className);

FirebaseMessaging.instance.onTokenRefresh.listen((newToken) {
  log('New Token $newToken', name: _className);

});


//it opens the app if terminated on notification tap
await FirebaseMessaging.instance.getInitialMessage().then((message) async {
  if (message != null) {
    await LocalNotificationHandler.displayNotification(message);
    message.data.forEach((key, value) {
    });
  }
});

//foreground notification
FirebaseMessaging.onMessage.listen((message) {
  // Works and displays
  log('foreground onMessage', name: _className);

  if (message.notification != null) {
    log('title ${message.notification!.title}', name: _className);
    log('body ${message.notification!.body}', name: _className);
  }
  LocalNotificationHandler.displayNotification(message);
});

//Background but alive
FirebaseMessaging.onMessageOpenedApp.listen((message) {
  log('Background onMessageOpenedApp', name: _className);
  log('data ${message.data.toString()}', name: _className);
});

}

this code does not show me the permission request on android so as i understand it's implemented for IOS only and it prints 'User granted permission' as default.

 if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User declined or has not accepted permission');
    }

And Here is the local Notification Plugin code for displaying notification on Foreground

class LocalNotificationHandler {
  static const String _className = 'Local Notification Handler';
  static final FlutterLocalNotificationsPlugin _localNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  static void initialize() {
    const InitializationSettings initializationSettings =
        InitializationSettings(
      android: AndroidInitializationSettings('@mipmap/ic_launcher'),
    );
    _localNotificationsPlugin.initialize(initializationSettings,onSelectNotification: (String? data) async{
      if(data != null){
        log('_localNotificationsPlugin data $data', name: _className);
      }
    });
  }

  static Future<void> displayNotification(RemoteMessage message) async {
    try {
      final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      NotificationDetails notificationDetails = const NotificationDetails(
        android: AndroidNotificationDetails(
          //realestateid
          'realestateid', //channel id
          'realestate channel', //channel name
          importance: Importance.max,
          priority: Priority.high,
          playSound: true,

        ),
        iOS: IOSNotificationDetails(
          presentAlert: true,
          presentBadge: true,
          presentSound: true,
        )
      );

      await _localNotificationsPlugin.show(id, message.notification!.title,
          message.notification!.body, notificationDetails,payload: message.data['route']);
    } on Exception catch (e) {
      log('display Notification Exception $e', name: _className);
    }
  }
}

and initializing both of them in main.dart file

   //the top level func for terminated state
      await LocalNotificationHandler.displayNotification(message);

void main()async {
  WidgetsFlutterBinding.ensureInitialized();

  //FCM Notifications
  LocalNotificationHandler.initialize();
  await FCMNotification.initFireBase();
}

so if anyone could help me with this it'll be really appreciated. thanks in advance and sorry for the long post.


Solution

  • It turned out in my case was the issue with the emulator, but with real devices it works fine.