Flutter Firebase 消息未收到通知

and*_*ner 6 android firebase flutter firebase-cloud-messaging

我目前正在使用 firebase 消息处理颤振通知,但我无法收到任何通知。我通过服务器使用 发送通知curl,但是我可以让它在原生 android 应用程序(Android Studio)中工作,但不能在颤振中工作,任何帮助将不胜感激。下面是我的代码。

颤振通知代码

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");
});
}
}
Run Code Online (Sandbox Code Playgroud)

安卓工作室代码

@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});
    }
}
Run Code Online (Sandbox Code Playgroud)

服务端代码

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);
}
Run Code Online (Sandbox Code Playgroud)

编辑

我以某种方式可以收到通知,但我注意到我的状态栏没有收到通知,但它打印在控制台中,但是,当我关闭应用程序时,我可以收到通知。那么我如何在两种情况下都能收到通知呢?

Nea*_*arl 5

来自文档

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

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

这个

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

如果您的应用程序当前打开并在前台,即使发送成功,也不会显示通知。您可以通过打开通知事件处理程序中的小吃栏来确认这一点,如下所示:

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

如果您使用 Android 并且希望在前台显示通知,您可以flutter_local_notifications按照此处FCM 文档的建议使用包。


小智 -2

您可能会错过 android 的手动配置(如果需要,还有 ios),请参阅下面的链接

http://myhexaville.com/2018/04/09/flutter-push-notifications-with-firebase-cloud-messaging/