2

我正在尝试编写应用程序以通过Firebase云消息传递接收通知。最初,当我尝试通过Firebase控制台发送消息时,但当我尝试使用php webservice执行相同操作时,作为响应,它显示成功,但我没有收到消息,也无法通过Firebase控制台获得更多通知。请帮助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; 
?> 
+0

你什么时候回声'$ result'你得到任何错误? –

+0

不是。它显示成功,但是当我尝试将通知发送到我的设备但我没有收到通知时 –

回答

4

此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; 
?> 

P.S:我硬编码接收的令牌截至目前(用于测试目的)

+0

感谢您的支持,效果很好。虽然由于某种原因,如果我试图在'Authorization:key ='这样的变量中追加密钥。 $键,它不会工作。 – Eric

+1

我这样做,但仍然没有收到任何通知 –

1

您还没有发布什么你在echo $result后得到结果消息。所以现在你的代码去后,我发现:

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

此行是造成问题。你应该使用这样的:

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

等..

为了进一步清除,我们使用:

remoteMessage.getNotification().getBody()当我们在把我们送到FCM服务器的JSON对象notification 。而你的情况是不存在的,而不是你有data对象和我们使用:

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

+0

这不是我最关心的问题(和问题)。我的问题是,我尝试了两次编写代码。对于我试图编写的两个应用程序,我最初都是使用Firebase控制台获取通知,然后尝试执行php webservice,获得成功但未收到通知,然后我停止从Firebase控制台收到通知。 –

+0

尝试在'onMessageReceived()'中记录任何东西? –

+0

是的,我做过。 Log.i( “/> />”,MSG); –

1

试试这个:

<?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; 

?> 
+1

它适合你吗?另外,如果我希望通过POST请求传递**一个**注册令牌,而不是从表中获取数据值,那么我该怎么做呢? –

+0

是的,它为我工作。是的,要通过邮寄请求传递一个注册令牌,你会稍微改变代码。明天,我会向你展示代码。 – FireUser

+0

@PinakiAcharya如果你只想传递一个注册令牌,你可以使用'to => your_token'而不是'registration_ids'。 –

0
<?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'); 
} 



?> 

一个用户

0

这个工作对我来说...... FCM端点可能并不那么可靠。试试这个

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

只是这不改变任何东西。另外这个端点将继续存在,谷歌没有计划如他们的开发者视频中提到的那样废弃GCM。

还有一件事..有没有延迟,或者你根本没有收到消息。如果由于TCP超时问题而导致延迟。试试这个,让我知道。祝你好运 !!

相关问题