Firebase flutter推送通知在Android上不起作用

alen0pnh  于 2023-03-03  发布在  Flutter
关注(0)|答案(2)|浏览(216)

我已经注册了我的应用程序,添加了google-services.json文件到我的应用程序文件夹。我添加了所需的depndcies等。我做的一切仍然当我从firebase控制台发送通知时,我没有收到我的应用程序是否最小化或前台。我甚至没有看到我的调试控制台中的东西。我的AVD也有Google Play服务。

jgovgodb

jgovgodb1#

1.在firebase网站注册你的应用程序(请注意你的应用程序id);
1.获取google-services.json并将其添加到"android-〉应用程序"文件夹;
1.更新你的应用id,使它和firebase中的一样;您可以通过添加元数据来更新应用程序图标:

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/app_icon" />

1.添加依赖项:(使用最新版本)

firebase_core: ^1.4.0
  firebase_messaging: ^10.0.4

1.在runApp()之上的main方法中添加await Firebase. initializeApp();

await Firebase.initializeApp();
  await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

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

试试这个,希望有用。不幸的是,我不记得所有的细节。

ckx4rj1h

ckx4rj1h2#

1.在firebase中注册您的应用程序;
2.将google-services.json添加到"安卓-〉应用程序";
3.在应用程序内的Android Mainfiest.xml中添加代码

<meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="high_importance_channel" />

    <meta-data android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_launcher" />

[在mainfiest open Image中使用前请检查图像]
4.添加依赖项:(使用最新版本)

firebase_core: ^2.7.0
firebase_messaging: ^14.2.5
flutter_local_notifications: ^13.0.0

5.在主方法中添加等待Firebase. initializeApp()

void main() async {
     await initializeFirebase();
     await getFcmToken();
     await NotificationService().init();
}

  Future initializeFirebase() async {
    await Firebase.initializeApp(
    name: "Your App Name",
    options: DefaultFirebaseOptions.currentPlatform,);
}

6.I为推送通知创建了通知服务类:

class NotificationService {
  static final NotificationService _notificationService = 
  NotificationService._internal();

 factory NotificationService() {
  return _notificationService;
 }

 NotificationService._internal(); 
 
 AndroidNotificationChannel channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description: 'This channel is used for important notifications.',
playSound: true,
// description
importance: Importance.high,);

final BehaviorSubject<String?> selectNotificationSubject = 
BehaviorSubject<String?>();

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = 
FlutterLocalNotificationsPlugin();

Future<void> init() async {
_configureSelectNotificationSubject();
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/logo');
DarwinInitializationSettings initializationSettingsDarwin =
DarwinInitializationSettings(
  requestSoundPermission: true,
  requestBadgePermission: true,
  requestAlertPermission: true,
  onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
InitializationSettings initializationSettings = InitializationSettings(
  android: initializationSettingsAndroid,
  iOS: initializationSettingsDarwin,
  macOS: null,
);

await flutterLocalNotificationsPlugin.initialize(
  initializationSettings,
  onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) {
    if (notificationResponse.notificationResponseType ==
        NotificationResponseType.selectedNotification) {
      selectNotificationSubject.add(notificationResponse.payload);
    }
  },
);

await flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onDidReceiveNotificationResponse: onSelectNotification,);

await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<
    AndroidFlutterLocalNotificationsPlugin>()
    ?.createNotificationChannel(channel);

await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<
    IOSFlutterLocalNotificationsPlugin>()
    ?.requestPermissions(
  alert: true,
  badge: true,
  sound: true,
);

await FirebaseMessaging.instance
    .setForegroundNotificationPresentationOptions(
  alert: true,
  badge: true,
  sound: true,
);

initFirebaseListeners();}

void _configureSelectNotificationSubject() {
selectNotificationSubject.stream.listen((String? payload) async {
  if (SharedPreferenceHelper().getUserToken() == null) {
    return;
  }
  NotificationEntity? entity =
  SharedPreferenceHelper().convertStringToNotificationEntity(payload);
  debugPrint(
      "notification _configureSelectNotificationSubject ${entity
          .toString()}");
  if (entity != null) {
    setRedirectionFromForeground
  }
});}

Future? onDidReceiveLocalNotification(int id, String? title, String? body, String? payload) {
if (SharedPreferenceHelper().getUserToken() == null) {
  return null;
}
NotificationEntity? entity =
SharedPreferenceHelper().convertStringToNotificationEntity(payload);
debugPrint(
    "notification onDidReceiveLocalNotification ${entity.toString()}");
if (entity != null) {
 setRedirectionFromForeground
}
return null;}
void initFirebaseListeners() {
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  if (SharedPreferenceHelper().getUserToken() == null) {
    debugPrint("userToken is Null");
    return;
  }

  debugPrint("OnMessageOpened notification opened ${message.data}");
  NotificationEntity notificationEntity =
  NotificationEntity.fromJson(message.data);
  setRedirectionFromForeground
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
  if (GetPlatform.isIOS ||
      SharedPreferenceHelper().getUserToken() == null) {

    return;
  }
  debugPrint("Foreground notification received  ${message.data}");
  NotificationEntity notificationEntity =
  NotificationEntity.fromJson(message.data);

  debugPrint(message.data.toString());
  notificationEntity.title = "App Name";
  notificationEntity.body = notificationEntity.body;
  showNotifications(notificationEntity);
});}

Future? onSelectNotification(NotificationResponse notificationResponse) {
if (SharedPreferenceHelper().getUserToken() == null) {
  return null;
}
NotificationEntity? entity =
SharedPreferenceHelper().convertStringToNotificationEntity(notificationResponse.payload);
debugPrint("notification onSelectNotification ${entity.toString()}");
if (entity != null) {
  setRedirectionFromForeground
}
return null;
}

Future<void> showNotifications(NotificationEntity notificationEntity) async {
Random random = Random();
int id = random.nextInt(900) + 10;
await flutterLocalNotificationsPlugin.show(
    id,
    notificationEntity.title,
    notificationEntity.body,
    NotificationDetails(
      android: AndroidNotificationDetails(
        channel.id,
        channel.name,
        channelDescription: channel.description,
        icon: "@mipmap/logo",
        channelShowBadge: true,
        playSound: true,
        priority: Priority.high,
        importance: Importance.high,
        styleInformation: BigTextStyleInformation(notificationEntity.body!),
      ),

      iOS: DarwinNotificationDetails(
        presentBadge: true,
        presentSound: true,
        presentAlert: true,
        badgeNumber: 1,
      )

    ),
    payload: SharedPreferenceHelper()
        .convertNotificationEntityToString(notificationEntity));}
 void pushNextScreenFromForeground(NotificationEntity notificationEntity) async {
SharedPreferenceHelper preferenceHelper = SharedPreferenceHelper();
Utils.showLoader();
Tuple2<String, Object>? tuple2 = await callApi(notificationEntity);
await Utils.hideLoader();
debugPrint("current active screen ${Get.currentRoute}");
if (tuple2 != null) {
   //Set Redirection
  }
  Get.toNamed(tuple2.item1, arguments: tuple2.item2);
}}}

相关问题