Firebase消息在设备上接收,但不会通过通知显示

时间:2017-06-19 02:49:22

标签: php android firebase push-notification firebase-cloud-messaging

我尝试将Firebase云消息传递(我使用this code mirrored here)与现有应用集成。

相关代码:

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脚本发送消息。服务器设法成功发送消息,例如:

  

{&#34; MESSAGE_ID&#34;: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:   数据有效负载:   {消息= {&#34;数据&#34; {&#34;图像&#34;:&#34;&#34;&#34; is_background&#34;:假,&#34;有效载荷&#34 ;:{&#34;杆&#34;:&#34; XYZ&#34;&#34;富&#34;:&#34; 123&#34;}&#34;标题&#34;:& #34;测试&#34;&#34;消息&#34;:&#34; mehehehe&#34;&#34;时间戳&#34;:&#34; 2017年6月19日   2:26:21&#34;}}} 06-19 09:26:21.600 18604-19560 / net.anta40.app.firebasetest   E / MyFirebaseMessagingService:push json:   {&#34;消息&#34; {&#34;数据&#34; {&#34;时间戳&#34;:&#34; 2017年6月19日   2:26:21&#34;&#34;消息&#34;:&#34; mehehehe&#34;&#34;有效载荷&#34; {&#34; BAR&#34;:&#34; XYZ&#34;&#34;富&#34;:&#34; 123&#34;}&#34;图像&#34;:&#34;&#34;&#34;标题&#34; :&#34;测试&#34;&#34; is_background&#34;:假}}}   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:控制接口命令   &#39; SIGNAL_POLL&#39;

但未通过通知显示。这里出了什么问题?

1 个答案:

答案 0 :(得分:1)

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

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

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

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

如果你打算使用notification - 仅有效负载,你可以简单地构建它:

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

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

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

在Android中,每种消息类型的处理方式都不同(请参阅Handling Messages)。

一些有用的帖子: