setting custom ringtone when in foreground working fine but in background not working

hi i am trying to implement custom ringtone when get notification in foreground working fine ringtone playing and stopping fine but when the app is in background the ringtone is ringing but Unable to stop it what i find is handleBackgroundMessage is creating new instance and in MyApp having diffrent instance of objects and

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  NotificationHandler().onSelectNotification(json.encode(message.data));
});

this method is called from Myapp so it has diffrent instance can anybody suggest what i am doing wrong here my code is below

   Future<void> handleBackgroundMessage(RemoteMessage message) async {
   if (Platform.isAndroid) {
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform);
   } else if (Platform.isIOS) {
    await Firebase.initializeApp();
    }
  final liveAstrologerController = Get.put(LiveAstrologerController());
 final walletController = Get.put(WalletController());
 final chatController = Get.put(ChatController);
  final callController = Get.put(CallController());
 final reportController = Get.put(ReportController());
 if (message.notification!.title == "For Live Streaming Chat") {
   Future.delayed(const Duration(milliseconds: 500)).then((value) async {
      await localNotifications.cancelAll();
    });
String sessionType = message.data["sessionType"];
if (sessionType == "start") {
  String? liveChatUserName2 = message.data['liveChatSUserName'];
  if (liveChatUserName2 != null) {
    liveAstrologerController.liveChatUserName = liveChatUserName2;
    liveAstrologerController.update();
  }
  String chatId = message.data["chatId"];
  liveAstrologerController.isUserJoinAsChat = true;
  liveAstrologerController.update();
  liveAstrologerController.chatId = chatId;
  int waitListId = int.parse(message.data["waitListId"].toString());
  String time = liveAstrologerController.waitList
      .where((element) => element.id == waitListId)
      .first
      .time;
     liveAstrologerController.endTime = DateTime.now().millisecondsSinceEpoch +
       1000 * int.parse(time.toString());
       liveAstrologerController.update();
   } else {}
     } else if (message.notification!.title ==
        "For timer and session start for live") {
     liveAstrologerController.update();
  } else if (message.notification!.title == "Start simple chat timer") {
 } else {
try {
  if (message.data.isNotEmpty) {
    var messageData = json.decode((message.data['body']));

    if (messageData['notificationType'] != null) {
      if (messageData['notificationType'] == 7) {
        // get wallet api call
        await walletController.getAmountList();
      } else if (messageData['notificationType'] == 8) {
        chatController.startRingTone();
        //AlarmHandler.scheduleAlarm();
        chatController.chatList.clear();
        chatController.update();

        await chatController.getChatList(false);
        debugPrint('chat resp-> $messageData');
      } else if (messageData['notificationType'] == 2) {
        //in background
        callController.startRingTone();

        await callController.getCallList(false);
      } else if (messageData['notificationType'] == 9) {
        reportController.reportList.clear();
        reportController.update();
        await reportController.getReportList(false);
      } else if (messageData['notificationType'] == 12 ||
          messageData['notificationType'] == 11 ||
          messageData['notificationType'] == 10) {
        liveAstrologerController.isUserJoinWaitList = true;
        liveAstrologerController.update();
      }
    }
  }
} catch (e) {
  debugPrint("Exception in _firebaseMessagingBackgroundHandler else $e");
}
 }
}

and myapp is

 void main() async {
  WidgetsFlutterBinding.ensureInitialized();
 await EasyLocalization.ensureInitialized();
 await GetStorage.init();
 await AndroidAlarmManager.initialize();

 if (Platform.isAndroid) {
   await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform);
 } else if (Platform.isIOS) {
      await Firebase.initializeApp();
 }

 HttpOverrides.global = MyHttpOverrides();

runApp(
   EasyLocalization(
     supportedLocales: const [
       Locale('en', 'US'),
     ],
     path: 'assets/translations',
    fallbackLocale: const Locale('en', 'US'),
    startLocale: const Locale('en', 'US'),
   child: const MyApp(),
 ),
 );
 }

 class MyApp extends StatefulWidget {
      const MyApp({super.key});

    @override
    State<MyApp> createState() => _MyAppState();
   }

  class _MyAppState extends State<MyApp> {
     dynamic analytics;
     final apiHelper = APIHelper();

    dynamic observer;
    final liveAstrologerController = Get.put(LiveAstrologerController());
    final walletController = Get.put(WalletController());
    final chatController = Get.put(ChatController());
    final callController = Get.put(CallController());
    final timerController = Get.put(TimerController());
    final reportController = Get.put(ReportController());
    final networkController = Get.put(NetworkController());

 @override
  void initState() {
     super.initState();
     log('chat hascode MyApp ${chatController.hashCode}');
     log('call hascode MyApp ${callController.hashCode}');
    inthandlerbackgroudn();

  FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
  if (message.notification!.title == "For Live Streaming Chat") {
    String sessionType = message.data["sessionType"];
    if (sessionType == "start") {
      String? liveChatUserName2 = message.data['liveChatSUserName'];
      if (liveChatUserName2 != null) {
        liveAstrologerController.liveChatUserName = liveChatUserName2;
        liveAstrologerController.update();
      }
      String chatId = message.data["chatId"];
      liveAstrologerController.isUserJoinAsChat = true;
      liveAstrologerController.update();
      liveAstrologerController.chatId = chatId;
      int waitListId = int.parse(message.data["waitListId"].toString());
      String time = liveAstrologerController.waitList
          .where((element) => element.id == waitListId)
          .first
          .time;
      liveAstrologerController.endTime =
          DateTime.now().millisecondsSinceEpoch +
              1000 * int.parse(time.toString());
      liveAstrologerController.update();
    } else {
      if (liveAstrologerController.isOpenPersonalChatDialog) {
        Get.back(); //if chat dialog opended
        liveAstrologerController.isOpenPersonalChatDialog = false;
      }
      liveAstrologerController.isUserJoinAsChat = false;
      liveAstrologerController.chatId = null;
      liveAstrologerController.update();
    }
  } else if (message.notification!.title ==
      "For timer and session start for live") {
    int waitListId = int.parse(message.data["waitListId"].toString());
    liveAstrologerController.joinedUserName =
        message.data["name"] ?? "User";
    liveAstrologerController.joinedUserProfile =
        message.data["profile"] ?? "";
    String time = liveAstrologerController.waitList
        .where((element) => element.id == waitListId)
        .first
        .time;
    liveAstrologerController.endTime =
        DateTime.now().millisecondsSinceEpoch +
            1000 * int.parse(time.toString());
    liveAstrologerController.update();
  } else if (message.notification!.title == "Start simple chat timer") {
    chatController.newIsStartTimer = true;
    chatController.update();

    timerController.endTime =
        DateTime.now().millisecondsSinceEpoch + 1000 * 300;
    timerController.update();
  } else if (message.notification!.title == "End chat from customer") {
    log('isInChatScreen ${chatController.isInChatScreen}');

    if (chatController.isInChatScreen) {
      chatController.updateChatScreen(false);
      apiHelper.setAstrologerOnOffBusyline("Online");
      chatController.update();

      //  Get.back();
    } else {
      log('do nothing chat dismiss');
    }
  } else if (message.notification!.title ==
      "Reject call request from astrologer") {
    print('user Rejected call request:-');
    callController.isRejectCall = true;
    callController.update();
    callController.rejectDialog();
  } else {
    try {
      if (message.data.isNotEmpty) {
        var messageData = json.decode((message.data['body']));

        log('noti body $messageData');
        if (messageData['notificationType'] != null) {
          if (messageData['notificationType'] == 7) {
            // get wallet api call
            await walletController.getAmountList();
            NotificationHandler().foregroundNotification(message);
            await FirebaseMessaging.instance
                .setForegroundNotificationPresentationOptions(
                    alert: true, badge: true, sound: true);
          } else if (messageData['notificationType'] == 8) {
            log('inside foreground noti type 8');
            chatController.startRingTone();
            chatController.chatList.clear();
            chatController.update();
            await chatController.getChatList(false);
            NotificationHandler().foregroundNotification(message);
            await FirebaseMessaging.instance
                .setForegroundNotificationPresentationOptions(
                    alert: true, badge: true, sound: true);

            //SHOW CHAT DIALOG
          } else if (messageData['notificationType'] == 2) {
            callController.startRingTone();

            log('iniside noti type 2');
            callController.callList.clear();
            callController.update();
            await callController.getCallList(false);
            NotificationHandler().foregroundNotification(message);
            await FirebaseMessaging.instance
                .setForegroundNotificationPresentationOptions(
                    alert: true, badge: true, sound: true);
          } else if (messageData['notificationType'] == 9) {
            reportController.reportList.clear();
            reportController.update();
            await reportController.getReportList(false);
            NotificationHandler().foregroundNotification(message);
            await FirebaseMessaging.instance
                .setForegroundNotificationPresentationOptions(
                    alert: true, badge: true, sound: true);
          } else if (messageData['notificationType'] == 12 ||
              messageData['notificationType'] == 11 ||
              messageData['notificationType'] == 10) {
            liveAstrologerController.isUserJoinWaitList = true;
            liveAstrologerController.update();
            NotificationHandler().foregroundNotification(message);
            await FirebaseMessaging.instance
                .setForegroundNotificationPresentationOptions(
                    alert: true, badge: true, sound: true);
          } else {
            NotificationHandler().foregroundNotification(message);
            await FirebaseMessaging.instance
                .setForegroundNotificationPresentationOptions(
                    alert: true, badge: true, sound: true);
          }

          NotificationHandler().foregroundNotification(message);
          await FirebaseMessaging.instance
              .setForegroundNotificationPresentationOptions(
                  alert: true, badge: true, sound: true);
        } else {
          NotificationHandler().foregroundNotification(message);
          await FirebaseMessaging.instance
              .setForegroundNotificationPresentationOptions(
                  alert: true, badge: true, sound: true);
        }
      } else {
        NotificationHandler().foregroundNotification(message);
        await FirebaseMessaging.instance
            .setForegroundNotificationPresentationOptions(
                alert: true, badge: true, sound: true);
      }
    } catch (e) {
      NotificationHandler().foregroundNotification(message);
      await FirebaseMessaging.instance
          .setForegroundNotificationPresentationOptions(
              alert: true, badge: true, sound: true);
    }
  }
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  NotificationHandler().onSelectNotification(json.encode(message.data));
   });
 }
 SplashController splashController = Get.put(SplashController());
  @override
  Widget build(BuildContext context) {
     return GetBuilder<SplashController>(builder: (s) {
       return Sizer(
         builder: (context, orientation, deviceType) => GetMaterialApp(
      debugShowCheckedModeBanner: false,
      navigatorKey: Get.key,
      enableLog: true,
      theme: Themes.light,
      darkTheme: Themes.dark,
      themeMode: ThemeService().theme,
      locale: context.locale,
      localizationsDelegates: [
        ...context.localizationDelegates,
        FallbackLocalizationDelegate()
      ],
      supportedLocales: context.supportedLocales,
      initialBinding: NetworkBinding(),
      title: global.appName,
      initialRoute: "SplashScreen",
      home: SplashScreen(
        a: analytics,
        o: observer,
         ),
      
       ),
     );
   });
}

void inthandlerbackgroudn() async {
   FirebaseMessaging messaging = FirebaseMessaging.instance;
   FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
   await messaging.requestPermission(
   alert: true,
   announcement: false,
   badge: true,
   carPlay: false,
   criticalAlert: false,
    provisional: false,
    sound: false,
   );
 }
 }

and my NotificaitonHandler class is

 class NotificationHandler {
      final localNotifications = FlutterLocalNotificationsPlugin();
      WalletController walletController = Get.put(WalletController());
      ReportController reportController = Get.put(ReportController());
      HomeController homecontroller = Get.put(HomeController());
      SignupController signupController = Get.put(SignupController());
      ChatController chatController = Get.find<ChatController>();
      CallController callController = Get.find<CallController>();

Future<void> onSelectNotification(String payload) async {
  Map<dynamic, dynamic> messageData;
  try {
    messageData = json.decode(payload);
  Map<dynamic, dynamic> body;
  body = jsonDecode(messageData['body']);
  if (body["notificationType"] == 7) {
    await walletController.getAmountList();
    Get.to(() => WalletScreen());
  } else if (body["notificationType"] == 8) {
    chatController.stopRingtone();
    Get.find<HomeController>().homeTabIndex = 0;
    Get.find<HomeController>().update();
    Get.to(() => const HomeScreen());
  } else if (body["notificationType"] == 2) {
    callController.stopRingtone();
    debugPrint('list length ${callController.callList.length}');
    callController.callList
        .removeWhere((call) => call.callId == body['callId']);
    callController.update();
    if (body['call_type'].toString() == '10') {
      callController.acceptCallRequest(
          body['callId'],
          body['profile'],
          body['name'],
          body['id'],
          body['fcmToken'],
          body['call_duration']);
    } else if (body['call_type'].toString() == '11') {
      callController.acceptVideoCallRequest(
          body['callId'],
          body['profile'],
          body['name'],
          body['id'],
          body['fcmToken'],
          body['call_duration']);
    }
    Get.find<HomeController>().homeTabIndex = 2; //pageview index
    Get.find<HomeController>().isSelectedBottomIcon = 1; // bottom bar index
    Get.find<HomeController>().update();
  } else if (body["notificationType"] == 9) {
  } else if (body["notificationType"] == 13) {
    if (Get.find<HomeController>().notificationHandlingremoteUID != 0) {
      global.showToast(message: 'You are already live, end call first');
    } else {}
  }
} catch (e) {
  debugPrint(
    'Exception in onSelectNotification main.dart:- ${e.toString()}',
  );
}

}

  Future<void> foregroundNotification(RemoteMessage payload) async {
     final DarwinInitializationSettings initializationSettingsDarwin =
        DarwinInitializationSettings(
      defaultPresentBadge: true,
      requestSoundPermission: true,
      requestBadgePermission: true,
     defaultPresentSound: true,
     onDidReceiveLocalNotification: (id, title, body, payload) async {
        debugPrint("object notification call");
      return;
    },
  );
   AndroidInitializationSettings android =
    const AndroidInitializationSettings('@mipmap/ic_launcher');
final InitializationSettings initialSetting = InitializationSettings(
    android: android, iOS: initializationSettingsDarwin);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initialSetting,
    onDidReceiveNotificationResponse: (_) {
  NotificationHandler().onSelectNotification(json.encode(payload.data));
});
AndroidNotificationChannel channel = const AndroidNotificationChannel(
  ' local notifications',
  'High Importance Notifications for ',
  importance: Importance.high,
);

AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
  channel.id,
  channel.name,
  importance: Importance.max,
  priority: Priority.high,
  icon: "@mipmap/ic_launcher",
  playSound: false,
  styleInformation: const BigTextStyleInformation(''),
);
const DarwinNotificationDetails iOSDetails = DarwinNotificationDetails();
NotificationDetails platformChannelSpecifics =
    NotificationDetails(android: androidDetails, iOS: iOSDetails);
global.sp = await SharedPreferences.getInstance();
if (global.sp!.getString("currentUser") != null) {
  await flutterLocalNotificationsPlugin.show(
    0,
    payload.notification!.title,
    payload.notification!.body,
    platformChannelSpecifics,
    payload: json.encode(payload.data.toString()),
  );
}

}
}
i am getting two different hascode of chatcontroller instance in my app and onselected notification has

[log] chat hascode MyApp 445182886
[log] chat hascode bghandler 668612596
[log] chat hascode NotificationHandler 445182886

                            

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật