我正在尝试使用Firebase将推送通知从一个Android设备发送到另一台Android设备,Firebase功能上的日志文件显示成功,但设备未收到通知。我尝试将推送通知手动发送到'notification'主题,它可以工作,但是在设备之间不起作用。我的代码有什么问题吗?
index.js:
// imports firebase-functions module
const functions = require('firebase-functions');
// imports firebase-admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/* Listens for new messages added to /messages/:pushId and sends a
notification to subscribed users */
exports.pushNotification =
functions.database.ref('/messages/{pushId}').onWrite((change,context) => {
console.log('Push notification event triggered');
/* Grab the current value of what was written to the Realtime Database */
var valueObject = change.after.val();
/* Create a notification and data payload. They contain the notification
information, and message to be sent respectively */
const payload = {
notification: {
title: valueObject.title,
body: valueObject.message,
sound: "default"
},
data:{
title: valueObject.title,
message: valueObject.message
}
};
/* Create an options object that contains the time to live for the
notification and the priority. */
const options = {
priority: "high",
timeToLive: 60 * 60 * 24 //24 hours
};
console.log('Title : ',valueObject.title);
console.log('Message : ',valueObject.message);
return admin.messaging().sendToTopic('notifications', payload, options);
});
MainActivity:
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.messaging.FirebaseMessaging;
public class MainActivity extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef;
String dataTitle, dataMessage;
EditText title, message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Handle possible data accompanying notification message.
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
if (key.equals("title")) {
dataTitle=(String)getIntent().getExtras().get(key);
}
if (key.equals("message")) {
dataMessage = (String)getIntent().getExtras().get(key);;
}
}
showAlertDialog();
}
database = FirebaseDatabase.getInstance();
myRef = database.getReference("messages");
title = (EditText) findViewById(R.id.title);
message = (EditText) findViewById(R.id.message);
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Message");
builder.setMessage("title: " + dataTitle + "\n" + "message: " +
dataMessage);
builder.setPositiveButton("OK", null);
builder.show();
}
public void subscribeToTopic(View view) {
FirebaseMessaging.getInstance().subscribeToTopic("notifications")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
String msg = "Subscribed to Topic: Notifications";
if (!task.isSuccessful()) {
msg = "Failed to Subscribed to Topic:
Notifications";
}
Log.d("Firebase", msg);
Toast.makeText(MainActivity.this, msg,
Toast.LENGTH_SHORT).show();
}
});
}
public void sendMessage(View view) {
myRef.push().setValue(new Message(title.getText().toString(),
message.getText().toString()));
Toast.makeText(this, "Message Sent", Toast.LENGTH_SHORT).show();
}
}
消息:
public class Message {
private String title, message;
public Message(){}
public Message(String title, String message) {
this.title = title;
this.message = message;
}
public String getTitle() {
return title;
}
public String getMessage() {
return message;
}
}
FCM服务:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FCMService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String notificationTitle = null, notificationBody = null;
String dataTitle = null, dataMessage = null;
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " +
remoteMessage.getData().get("message"));
dataTitle = remoteMessage.getData().get("title");
dataMessage = remoteMessage.getData().get("message");
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " +
remoteMessage.getNotification().getBody());
notificationTitle = remoteMessage.getNotification().getTitle();
notificationBody = remoteMessage.getNotification().getBody();
}
// Also if you intend on generating your own notifications as a result
of a received FCM
// message, here is where that should be initiated. See
sendNotification method below.
sendNotification(notificationTitle, notificationBody, dataTitle,
dataMessage);
}
/**
// * Create and show a simple notification containing the received FCM
message.
// */
private void sendNotification(String notificationTitle, String
notificationBody, String dataTitle, String dataMessage) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("title", dataTitle);
intent.putExtra("message", dataMessage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /*
Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri=
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */,
notificationBuilder.build());
}
}
日志:
7:35:01.589 AM
pushNotification
Function execution took 1016 ms, finished with status: 'ok'
7:35:00.895 AM
pushNotification
Message : Raman
7:35:00.895 AM
pushNotification
Title : Raman
7:35:00.810 AM
pushNotification
Push notification event triggered