Firebase云消息传递,接收通知中的问题 [英] Firebase Cloud Messaging, issues in receiving notification

查看:817
本文介绍了Firebase云消息传递,接收通知中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写应用程序以通过Firebase云消息传递接收通知。最初,当我尝试通过Firebase控制台发送消息时,但当我尝试使用php webservice执行相同操作时,作为响应,它显示成功,但我没有收到消息,也无法通过Firebase控制台获得更多通知。请帮忙

我的服务器端代码:

MainActivity.java

  package com.example.mojojojo.firebasenotifications; 

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

import com.google.firebase.iid.FirebaseInstanceId;

公共类MainActivity扩展AppCompatActivity {

私有EditText etToken;
私人SharedPreferences sp;
私人SharedPreferences.Editor编辑;

@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));


信息服务 p>

  package com.example.mojojojo.firebasenotifications; 

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

导入com.google.firebase.messaging.FirebaseMessagingService;
导入com.google.firebase.messaging.RemoteMessage;

public class MessagingService extends FirebaseMessagingService {
$ b @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());
}
}

令牌服务 p>

  package com.example.mojojojo.firebasenotifications; 

导入android.app.Service;
导入android.content.Intent;
导入android.content.SharedPreferences;
导入android.os.IBinder;

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

公共类TokenService扩展FirebaseInstanceIdService {
私有SharedPreferences sp;
私人SharedPreferences.Editor编辑;

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

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

字符串标记= FirebaseInstanceId.getInstance()。getToken();
edit.putString(token,token);

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


清单

 <?xml version =1.0encoding =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>

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

< service
android:name =。MessagingService
android:enabled =false
android:exported =false>
< intent-filter>
< / intent-filter>
< / service>

< service
android:name =。TokenService>
< intent-filter>
< / intent-filter>
< / service>
< / application>

< / manifest>

和我的php代码如下键入代码)

 <?php 
define('API_ACCESS_KEY','YOUR-API-ACCESS- KEY-GOES-HERE');
$ registrationIds = array($ _GET ['id']);
//准备包
$ msg =数组

'message'=>'hi',
'title'=>'这是一个title',
'subtitle'=>'这是一个字幕。subtitle',
'tickerText'=>'此处的代码文本...此处的代码文本...此处的代码文本',
'vibrate'=> 1,
'sound'=> 1,
'largeIcon'=>'large_icon',
'smallIcon'=> 'small_icon'
);
$ fields = array

'registration_ids'=> $ registrationIds,
'data'=> $ msg
);

$ header = 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 
函数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

);

$ b $ header = 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);
返回$ result;
}
$ tokens = array('RECEIVER-TOKEN-1'
,'RECEIVER_TOKEN-2');

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

PS:我现在硬编码接收器令牌(用于测试目的)


I'm trying to write an application to receive notifications via Firebase Cloud Messaging. It initially worked when I tried to send the message via Firebase console but then the moment I tried doing the same using php webservice, in response, it showed success but I neither received the message nor am I able to get any more notifications via firebase console. Please help

My server side code:

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"));
    }
}

Messaging service

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());
    }
}

Token Service

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);
    }
}

Manifest

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

and my php code is as follows (I've removed the server Key in the code)

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

解决方案

This php code finally worked for me.

<?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: I've hard coded the receiver tokens as of now (for testing purposes)

这篇关于Firebase云消息传递,接收通知中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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