Untitled

mail@pastecode.io avatar
unknown
dart
24 days ago
9.1 kB
0
Indexable
Never
import 'dart:async';
import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';
import '../screens/notificationPage/components/noti_snack_bar.dart';
import './firebase_options.dart';

class NotificationHandler {
  //RemoteMessage? messaging =await FirebaseMessaging.instance.getInitialMessage();
  static final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  FirebaseMessaging messaging = FirebaseMessaging.instance;

  static final NotificationHandler _singlsdeton =
      NotificationHandler._singlsdeton;

  insertlistin() {
    localNotificationInitialize();
    permission();
    getmessange();
  }

  permission() async {
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: false,
      criticalAlert: true,
      provisional: true,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      // izin verildi
    } else if (settings.authorizationStatus ==
        AuthorizationStatus.provisional) {
      // geçici izin verildi
    } else {
      // Kullanıcı izni reddetti veya kabul etmedi
      try {
        if (Platform.isAndroid) {
          await Permission.notification.request();
        } else if (Platform.isIOS) {
          if (await Permission.notification.isDenied) {
            await openAppSettings();
          }
        }
      } catch (e) {
        //
      }
    }
  }

  /// uygulama açıkken gelen mesaj
  getmessange() async {
    try {
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        //RemoteNotification? notification = message.notification;
        //AndroidNotification? android = message.notification?.android;
        var messagedata = message.data;
        if (message.notification != null) {
          if (messagedata["title"] == null) {
            messagedata["title"] = message.notification!.title ?? "";
          }
          if (messagedata["description"] == null) {
            messagedata["description"] = message.notification!.body ?? "";
          }
        }
        // debugPrint(
        //     "************ notification_handler.dart : uygulama açıkken gelen mesaj : $messagedata");
        try {
          notiSnackBar(messagedata);
        } catch (e) {
          //
        }
      });

      ////ugulama arkaplanda veya kapalıyken gelecek mesaj
      /// Kullanıcı FCM aracılığıyla görüntülenen bir bildirim mesajına bastığında çağrılan [Stream] öğesini döndürür.
      FirebaseMessaging.onMessageOpenedApp
          .listen((RemoteMessage message) async {
        var messagedata = message.data;
        if (message.notification != null) {
          if (messagedata["title"] == null) {
            messagedata["title"] = message.notification!.title ?? "";
          }
          if (messagedata["description"] == null) {
            messagedata["description"] = message.notification!.body ?? "";
          }
        }

        // debugPrint(
        //     "************ notification_handler.dart : FirebaseMessaging.onMessageOpenedApp : $messagedata");
        notificationOnTapOpen(messagedata);
      });
    } catch (e) {
      debugPrint("*-*-*- 65 : ERROR : $e");
    }
  }

  static Future<void> showBigTextNotification({
    required String title,
    required String description,
    required String? image,
    required String? redirecttype,
    required String? redirectId,
    required Map<String, dynamic>? payload,
  }) async {
    try {
      //! Bildirim ikonu
      //! Uint8List? largeIcon = image == null ? null : await _getLargeIcon(image);

      bool isDM = false;
      bool isGroupMsg = false;

      if (redirecttype.toString() == "chatId") {
        isDM = true;
      } else if (redirecttype.toString() == "group") {
        isGroupMsg = true;
      }

      //! bigText baslangic
      var bigTextStyleInformation = BigTextStyleInformation(
        description.toString(),
        htmlFormatContent: true,
        htmlFormatTitle: true,
      );
      //! bigText bitiş

      //! mediaStyle baslangic
      // var mediaStyleInformation = MediaStyleInformation(
      //   htmlFormatContent: true,
      //   htmlFormatTitle: true,
      // );
      //! mediaStyle bitiş

      //! mesaj baslangic
      // Person person = Person(
      //   name: title,
      //   icon: image == null ? null : await _getShowNotiImage(image),
      //   important: isDM,
      // );
      // Message newNotifMsg = Message(
      //   description,
      //   DateTime.now(),
      //   person,
      // );
      // var messageStyleInformation = MessagingStyleInformation(
      //   person,
      //   groupConversation: isDM ? false : true,
      //   messages: [newNotifMsg],
      //   htmlFormatContent: true,
      //   htmlFormatTitle: true,
      // );
      //! mesaj bitis

      const iOSPlatformChannelSpecifics = DarwinNotificationDetails(
        sound: "true",
        presentAlert: true,
        presentSound: true,
      );

      var androidNotificationDetails = AndroidNotificationDetails(
        redirecttype ?? "Wipepp Notification",
        "Wipepp Notifications",
        channelDescription: "Wipepp Notifications.",
        importance: isDM ? Importance.high : Importance.max,
        styleInformation: bigTextStyleInformation,
      );

      NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails,
        iOS: iOSPlatformChannelSpecifics,
      );

      flutterLocalNotificationsPlugin.show(
        title.hashCode,
        title.toString(),
        description.toString(),
        notificationDetails,
        payload: payload.toString(),
      );
    } catch (e) {
      debugPrint(
        "notification_handler_194 -> showBigTextNotification ERROR(catch) : $e",
      );
    }
  }

  Future<void> localNotificationInitialize() async {
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    const DarwinInitializationSettings initializationSettingsIOS =
        DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
      //onDidReceiveLocalNotification: onDidReceiveLocalNotification,
    );

    const DarwinInitializationSettings initializationSettingsMacOS =
        DarwinInitializationSettings();

    const InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
      macOS: initializationSettingsMacOS,
    );

    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
    );
  }

  // static Future<ByteArrayAndroidIcon?> _getShowNotiImage(
  //   String imageUrl,
  // ) async {
  //   final response = await http.get(Uri.parse(imageUrl));
  //   if (response.statusCode == 200) {
  //     final base64Image = base64Encode(response.bodyBytes);
  //     return ByteArrayAndroidIcon.fromBase64String(base64Image);
  //   } else {
  //     debugPrint('Photo_download_error_222: ${response.statusCode}');
  //     return null;
  //   }
  // }

  // static Future<Uint8List?> _getLargeIcon(String imageUrl) async {
  //   final response = await http.get(Uri.parse(imageUrl));
  //   if (response.statusCode == 200) {
  //     return Uint8List.fromList(response.bodyBytes);
  //   } else {
  //     debugPrint("notification_handler_129 -> _getLargeIcon : image error");
  //     return null;
  //   }
  // }
}

@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  debugPrint("_firebaseMessagingBackgroundHandler ******  : ${message.data}");

  await Firebase.initializeApp(
    name: "Wipepp",
    options: DefaultFirebaseOptions.currentPlatform,
  );

  var messagedata = message.data;

  NotificationHandler.showBigTextNotification(
    title: messagedata["title"],
    description: messagedata["description"],
    image: messagedata["image"],
    redirecttype: messagedata["redirecttype"],
    redirectId: messagedata["redirect"],
    payload: messagedata,
  );
}

@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {
  // debugPrint(
  //   '--------  notification(${notificationResponse.id}) action tapped: '
  //   '${notificationResponse.actionId} with'
  //   ' payload: ${notificationResponse.payload}',
  // );
  if (notificationResponse.input?.isNotEmpty ?? false) {
    // debugPrint(
    //   '----------  notification action tapped with input: ${notificationResponse.input}',
    // );
  }
}
Leave a Comment