Flutter Firebase Messaging收不到通知

12

我目前正在使用Firebase Messaging处理Flutter通知,但我无法接收任何通知。我使用curl通过服务器发送通知,在原生的Android应用程序(Android Studio)中可以正常工作,但在Flutter中无法工作,希望得到帮助。以下是我的代码。

Flutter通知代码

class FirebaseNotifications {
FirebaseMessaging _firebaseMessaging;

void setUpFirebase() {
_firebaseMessaging = FirebaseMessaging();
firebaseCloudMessaging_Listeners();
}

void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();

_firebaseMessaging.getToken().then((token) {
  print(token);
});

_firebaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    print('on message $message');
  },
  onResume: (Map<String, dynamic> message) async {
    print('on resume $message');
  },
  onLaunch: (Map<String, dynamic> message) async {
    print('on launch $message');
  },
);
}

void iOS_Permission() {
_firebaseMessaging.requestNotificationPermissions(
    IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered
    .listen((IosNotificationSettings settings) {
  print("Settings registered: $settings");
});
}
}

Android Studio 代码

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Map<String, String> params = remoteMessage.getData();

    JSONObject object = new JSONObject(params);

    showNotification(remoteMessage);
}

private void showNotification(RemoteMessage remoteMessage) { 
Map data = remoteMessage.getData();

String mesg = "New Notification";

Intent intent;
    PendingIntent pendingIntent;
    NotificationCompat.Builder builder;

    Intent i = new Intent(this,MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.GREEN);
        mChannel.enableVibration(true);
        mChannel.setVibrationPattern(new long[]{0, 250, 250, 250});
        mNotificationManager.createNotificationChannel(mChannel);

        builder = new NotificationCompat.Builder(this, id);

        intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        builder.setContentTitle(data.get("title").toString())  // required
                //.setStyle(new 
 NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification()
.getBod 
y().toString()))
                .setStyle(new 
NotificationCompat.BigTextStyle().bigText(mesg)) //custom data
                .setSmallIcon(R.drawable.ic_stat_notification_icon4) // 
required
              
                .setContentText(mesg) // custom data
                .setWhen(System.currentTimeMillis())
                .setDefaults(Notification.DEFAULT_ALL)
                
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{0, 250, 250, 250});
    }
}

服务器端代码

function sendtoUser($sendingTarget, $acc_name, $type_message, 
$type_of_transaction, $check_amount)
{

#API access key from Google API's Console
$API_ACCESS_KEY = "adazxc";
$registrationIds = $sendingTarget;
#prep the bundle

$fields = array(
    'to'        => $registrationIds,
    'data' => array(
        'title' => 'my title',
        'keyValue' => true,
        'receiverName' => $acc_name,
        'transType' => $type_of_transaction,
        'totalAmount' => $check_amount
    ),
);

$headers = array(
    'Authorization: key=' . $API_ACCESS_KEY,
    'Content-Type: application/json'
);
#Send Reponse To FireBase Server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
}

编辑

我不知何故能够收到通知,但我注意到我的状态栏没有接收到通知,但它在控制台中打印出来了,然而,当我关闭应用程序时,我可以收到通知。那么我怎样才能在这两种情况下都能收到通知呢?


@androidnewbielearner 我也有同样的问题,你解决了吗? - Edeson Bizerril
6个回答

4

data标签只是用来向应用程序传输更多信息的,例如重定向位置、图像等。您需要添加notification标签以在状态栏上显示通知。

看起来您还没有添加通知内容,请参考以下示例消息并进行相同配置,它将正常工作。

{
   "notification": {
      "body": "body",
      "title": "title"
   },
   "priority": "high",
   "data": {
      "click_action": "FLUTTER_NOTIFICATION_CLICK",
      "id": "1",
      "status": "done",
      "image": "https://ibin.co/2t1lLdpfS06F.png",
   },
   "to": <fcm_token>
}

4

来自文档

根据设备状态,处理传入消息的方式不同。

状态 描述
前台 当应用程序打开、在视图中且正在使用时。
后台 当应用程序打开但在后台(最小化)时。这通常发生在用户按下设备上的“主页”按钮、通过应用切换器切换到另一个应用程序或在不同选项卡(Web)上打开应用程序时。
终止 当设备被锁定或应用程序未运行时。用户可以通过设备上的应用程序切换器 UI “滑动关闭” 应用程序或关闭选项卡(Web)来终止应用程序。

这个:

默认情况下,在应用程序处于前台时到达的通知消息不会显示可见通知。

如果您的应用程序当前已打开且在前台,则即使成功发送通知,该通知也不会显示。您可以通过在通知事件处理程序中打开snackbar来确认此操作,如下所示:

FirebaseMessaging.onMessage.listen((message) {
  print('Got a message whilst in the foreground!');

  if (message.notification != null) {
    final snackBar = SnackBar(
      content: Text(message.notification?.title ?? '', maxLines: 2),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }
});

如果你正在使用安卓系统,并且想在前台时显示通知,可以使用flutter_local_notifications包,正如FCM文档这里所建议的。


2

一些检查(版本号可能会改变):

  • 将google-services.json (从Firebase控制台下载) 添加到android/app/

在 android/build.gradle 中:

  • 将 google() 添加到 repositories
  • 将 classpath 'com.google.gms:google-services:4.2.0' 添加到 dependencies

在 android/app/build.gradle 中:

  • 将 implementation 'com.google.firebase:firebase-messaging:18.0.0' 添加到 dependencies
  • 在结尾处添加 apply plugin: 'com.google.gms.google-services'
  • 应用程序ID与 google-services.json 中的 package_name 相同
<最初的回答>

7
我可以收到通知,但发现状态栏没有显示通知,而在控制台中有打印信息。但是当我关闭应用程序时,我可以收到通知。那么我该如何在这两种情况下都能接收通知呢? - androidnewbielearner
1
我遇到了同样的问题,你是如何解决的? - kenn
在Flutter中,androidnewbielearner和kenn,前台通知将不会被显示。您的应用程序状态必须为“已终止”或“已挂起”才能接收通知。但是,在前台时,您必须接收有效负载。如果需要,您可以将该数据作为本地通知或警报呈现。 - Akash Neeli

2

就我所知,今天我遇到了一个问题,无法接收onMessage通知(没有尝试onResumeonLaunch),而昨天还能正常工作。函数日志中没有错误,令牌都是相同的。

尝试重新启动设备--如果您之前的函数可以正常工作,则这似乎是最一致的解决方法。

此外,如果消息似乎一开始很慢,这可能是由于长时间不使用函数时的冷启动(请参见此SO question以获取更多信息)。


0

这里已经提到了大多数情况。但是,除了@Zerj提到的检查清单之外,我想再添加一点。

  • 检查您的项目是否有开发、暂存、生产等环境版本。在这种情况下,google-services.json文件将驻留在相应的文件夹中(android/app/development等),而不是在android/app级别。
  • 如果上述方法对您也有问题,您可以使用FirebaseOptions类在口味的MainActivity文件中硬编码凭据。您可以在此处找到用法。

关于风味的更多信息 - https://firebase.google.com/docs/projects/multiprojects


-2

此链接已损坏。 - Samuel Nde

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接