设备上收到Firebase消息,但未通过通知显示 [英] Firebase message is received on device but not displayed via notification

查看:72
本文介绍了设备上收到Firebase消息,但未通过通知显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试集成Firebase Cloud Messaging(我使用

I'm trying to integrate Firebase Cloud Messaging (I use this code, which is mirrored here) with my existing app.

相关代码:

service.php

$msg_id = $_POST['id'];
$title = $_POST['title'];
$content = $_POST['content'];
$msg_date = $_POST['date'];
$author = $_POST['author'];

// insert the message into DB               
$sql = "INSERT INTO tbl_message(msg_id, title, content, msg_date, author) VALUES ('$msg_id','$title','$content','$msg_date','$author')";

if ($result = mysqli_query($db, $sql)){

    $firebase = new Firebase();
    $push = new Push();

    $payload = array();
    $payload['foo'] = '123';
    $payload['bar'] = 'xyz';

    $push->setTitle($title);
    $push->setMessage($content);
    $push->setAuthor($author);
    $push->setDate($msg_date);
    $push->setImage('');
    $push->setPayload($payload);
    $push->setIsBackground(FALSE);
    $resp = '';
    $response = '';
    $resp = $push->getPush();
    $response = $firebase->sendToTopic('global', $resp);

    echo $response;
}

Firebase.php

<?php


class Firebase {

    // sending push message to single user by firebase reg id
    public function send($to, $message) {
        $fields = array(
            'to' => $to,
            //'data' => $message,
            'data' => array("message" => $message));

        return $this->sendPushNotification($fields);
    }

    // Sending message to a topic by topic name
    public function sendToTopic($to, $message) {
        $fields = array(
            'to' => '/topics/' . $to,
            //'data' => $message,
            'data' => array("message" => $message)
        );
        return $this->sendPushNotification($fields);
    }

    // sending push message to multiple users by firebase registration ids
    public function sendMultiple($registration_ids, $message) {
        $fields = array(
            'to' => $registration_ids,
            //'data' => $message,
            'data' => array("message" => $message)
        );

        return $this->sendPushNotification($fields);
    }

    // function makes curl request to firebase servers
    private function sendPushNotification($fields) {

        require_once 'config.php';

        // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';

        $headers = array(
            'Authorization: key=' . FIREBASE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        return $result;
    }
}

?>

MainActivity.java

package studio.emcorp.monitoringsiswa;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.messaging.FirebaseMessaging;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
;

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(NotificationConfig.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(NotificationConfig.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(NotificationConfig.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

                    //txtMessage.setText(message);
                }
            }
        };



    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(NotificationConfig.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(NotificationConfig.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtil.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}

直接从Firebase控制台发送消息效果很好.现在的问题是通过PHP脚本发送消息.服务器以某种方式设法成功发送消息,例如:

Sending messages directly from Firebase Console works fine. Now the problem is sending messages via PHP script. Somewhow the server manages to send the message successfuly, e.g:

{"message_id":4732936739964848111}

{"message_id":4732936739964848111}

,设备将收到它:

06-19 09:26:21.590 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService:发件人:/topics/global 06-19 09:26:21.590 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService: 数据有效负载: {message = {"data":{"image":","is_background":false,"payload":{"bar":"xyz","foo":"123"},"title":"test ,"消息:" mehehehe,"时间戳:" 2017-06-19 2:26:21}}} 06-19 09:26:21.600 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService:推送json: {"message":{"data":{"timestamp":"2017-06-19 2:26:21," message:" mehehehe," payload:{" bar:" xyz," foo:" 123}," image:"," title:" test ," is_background:false}}} 06-19 09:26:21.600 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService:Json异常:数据无值06-19 09:26:21.720 1098-1098/? D/wpa_supplicant:RX ctrl_iface- hexdump(len = 11):53 49 47 4e 41 4c 5f 50 4f 4c 4c 06-19 09:26:21.720 1098-1098/? D/wpa_supplicant:wlan0:控制接口命令 'SIGNAL_POLL'

06-19 09:26:21.590 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService: From: /topics/global 06-19 09:26:21.590 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService: Data Payload: {message={"data":{"image":"","is_background":false,"payload":{"bar":"xyz","foo":"123"},"title":"test","message":"mehehehe","timestamp":"2017-06-19 2:26:21"}}} 06-19 09:26:21.600 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService: push json: {"message":{"data":{"timestamp":"2017-06-19 2:26:21","message":"mehehehe","payload":{"bar":"xyz","foo":"123"},"image":"","title":"test","is_background":false}}} 06-19 09:26:21.600 18604-19560/net.anta40.app.firebasetest E/MyFirebaseMessagingService: Json Exception: No value for data 06-19 09:26:21.720 1098-1098/? D/wpa_supplicant: RX ctrl_iface - hexdump(len=11): 53 49 47 4e 41 4c 5f 50 4f 4c 4c 06-19 09:26:21.720 1098-1098/? D/wpa_supplicant: wlan0: Control interface command 'SIGNAL_POLL'

,但不会通过通知显示.这里出了什么问题?

but not displayed via notifications. What goes wrong here?

推荐答案

您正在发送 data - PHP中的有效负载:

You are sending a data-only payload in your PHP:

public function send($to, $message) {
    $fields = array(
        'to' => $to,
        //'data' => $message,
        'data' => array("message" => $message));

    return $this->sendPushNotification($fields);
}

您的其他方法也发送相同的内容.

如果要使用仅notification的有效负载,则可以像这样简单地构造它:

If you're going to use a notification-only payload, you could simply structure it like so:

public function send($to, $message) {
    $fields = array(
        'to' => $to,
        'notification' => array("title" => $title,
            "body" => $body));

    return $this->sendPushNotification($fields);
}

与从Firebase控制台发送消息的区别在于,来自控制台的消息被视为 notification 消息.

The difference from sending a message from the Firebase Console is that messages from the console are considered as notification messages.

在Android中,每种消息类型的处理方式都不同(请参见处理消息).

In Android, each message type is handled differently (see Handling Messages).

一些有用的帖子:

  • Issue with FCM notification
  • Can we push only data message from Firebase Notification console

这篇关于设备上收到Firebase消息,但未通过通知显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆