簡體   English   中英

Firebase Cloud Messaging,接收通知時出現問題

[英]Firebase Cloud Messaging, issues in receiving notification

我正在嘗試編寫一個應用程序以通過Firebase Cloud Messaging接收通知。 當我嘗試通過Firebase控制台發送消息時,它最初起作用了,但是當我嘗試使用php webservice進行相同操作時,作為響應,它顯示成功,但是我既沒有收到消息,也無法通過Firebase控制台獲得任何更多通知。 請幫忙

我的服務器端代碼:

MainActivity.java

package com.example.mojojojo.firebasenotifications;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;

import com.google.firebase.iid.FirebaseInstanceId;

public class MainActivity extends AppCompatActivity {

    private EditText etToken;
    private SharedPreferences sp;
    private SharedPreferences.Editor edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etToken=(EditText)findViewById(R.id.etToken);

        sp=getSharedPreferences("pref",MODE_PRIVATE);
        edit=sp.edit();

        etToken.setText(FirebaseInstanceId.getInstance().getToken());
        BroadcastReceiver tokenReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String token=intent.getExtras().getString("token");
                if(token!=null){
                    etToken.setText(token);
                }
            }
        };
        registerReceiver(tokenReceiver,new IntentFilter("TOKEN_GENERATED"));
    }
}

訊息服務

package com.example.mojojojo.firebasenotifications;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        String msg=remoteMessage.getNotification().getBody();
        sendNotification(msg);
        Log.i("/>/>",msg);
    }
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0 , notificationBuilder.build());
    }
}

代幣服務

package com.example.mojojojo.firebasenotifications;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class TokenService extends FirebaseInstanceIdService {
    private SharedPreferences sp;
    private SharedPreferences.Editor edit;

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();

        sp=getSharedPreferences("pref",MODE_PRIVATE);
        edit=sp.edit();

        String token= FirebaseInstanceId.getInstance().getToken();
        edit.putString("token",token);

        Intent tokenIntent=new Intent("TOKEN_GENERATED");
        tokenIntent.putExtra("token",token);
        sendBroadcast(tokenIntent);
    }
}

表現

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mojojojo.firebasenotifications">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MessagingService"
            android:enabled="false"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name=".TokenService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>

</manifest>

和我的PHP代碼如下 (我已經刪除了代碼中的服務器密鑰)

<?php
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
    'message'   => 'hi',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);
$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'          => $msg
);

$headers = array
(
    'Authorization: key=' . 'xxxxxxxxxxxxxxxxxxxxx',
    'Content-Type: application/json'
);

$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 );
echo $result;
?>

這個PHP代碼終於為我工作。

<?php 
function send_notification ($tokens)
{

    $url = 'https://fcm.googleapis.com/fcm/send';
    $priority="high";
    $notification= array('title' => 'Some title','body' => 'hi' );

    $fields = array(
         'registration_ids' => $tokens,
         'notification' => $notification

        );


    $headers = array(
        'Authorization:key=xxxxxxxxxxxxx',
        'Content-Type: application/json'
        );

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    // echo json_encode($fields);
   $result = curl_exec($ch);           
   echo curl_error($ch);
   if ($result === FALSE) {
       die('Curl failed: ' . curl_error($ch));
   }
   curl_close($ch);
   return $result;
}
$tokens = array('RECEIVER-TOKEN-1'
    ,'RECEIVER_TOKEN-2');

  $message_status = send_notification($tokens);
  echo $message_status;
?>

PS:到目前為止,我已經對接收器令牌進行了硬編碼(出於測試目的)

echo $result后,您還沒有發布結果消息。 因此,在檢查完您的代碼后,現在我發現:

String msg=remoteMessage.getNotification().getBody();

這條線引起問題。 您應該改為這樣使用它:

remoteMessage.getData().get("message")
remoteMessage.getData().get("title")
remoteMessage.getData().get("subtitle")

等等..

為了進一步清除,我們使用:

當我們在發送到fcm服務器的JSON中具有notification對象時, remoteMessage.getNotification().getBody() 在您的情況下不存在,而是您有data對象,為此,我們使用:

remoteMessage.getData().get("key_name")

嘗試這個:

<?php 

function send_notification ($tokens, $message)
{
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array(
         'registration_ids' => $tokens,
         'data' => $message
        );

    $headers = array(
        'Authorization:key = YOUR_KEY ',
        'Content-Type: application/json'
        );

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
   $result = curl_exec($ch);           
   if ($result === FALSE) {
       die('Curl failed: ' . curl_error($ch));
   }
   curl_close($ch);
   return $result;
}


$conn = mysqli_connect("localhost","root","","fcm");

$sql = " Select Token From users";

$result = mysqli_query($conn,$sql);
$tokens = array();

if(mysqli_num_rows($result) > 0 ){

    while ($row = mysqli_fetch_assoc($result)) {
        $tokens[] = $row["Token"];
    }
}

mysqli_close($conn);

   $message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
   $message_status = send_notification($tokens, $message);
   echo $message_status;

?>
    <?php 

    function send_notification ($tokens, $message)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        $fields = array(
             'registration_ids' => $tokens,
             'data' => $message
            );

        $headers = array(
            'Authorization:key = your token ',
            'Content-Type: application/json'
            );

       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
       $result = curl_exec($ch);           
       if ($result === FALSE) {
           die('Curl failed: ' . curl_error($ch));
       }
       curl_close($ch);
       return $result;
    }

//Checking post request 
if($_SERVER['REQUEST_METHOD']=='POST'){

    //Connection to database

    $conn = mysqli_connect("localhost","root","","bbdd");

     //Geting email and message from the request 

    $email = $_POST['Email'];
    $msg = $_POST['message'];

    //Getting the firebase id of the person selected to send notification
    $sql = "SELECT * FROM users WHERE email = '$email'";


    $result = mysqli_query($conn,$sql);
    $tokens = array();

    if(mysqli_num_rows($result) > 0 ){

        while ($row = mysqli_fetch_assoc($result)) {
            $tokens[] = $row["Token"];
        }
    }

    mysqli_close($conn);

    $message = array("message" =>"$msg");
    $message_status = send_notification($tokens, $message);
    echo $message_status;

    //redirecting back to the sendnotification page 
    header('Location: sendPushNotification.php?success');
}else{
    header('Location: sendPushNotification.php');
}



 ?>

給一個用戶

這對我有用... FCM端點可能不那么可靠。 嘗試這個

  $url = 'https://gcm-http.googleapis.com/gcm/send';

只是這不會改變任何其他東西。 同樣,此終結點將繼續存在,如他們的開發人員視頻中所述,谷歌沒有計划棄用GCM。

還有一件事..是否有延遲,或者您根本沒有收到消息。如果存在延遲,可能是由於TCP超時問題引起的。 試試這個,讓我知道。 祝好運 !!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM