我在个人项目中使用android + firebase。现在,我正在尝试在客户进行购买时向特定用户发送通知。我实现了一些关于fcm的教程,但我不知道为什么这些函数不起作用。 index.js是下一个:
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var request = require('request');
var API_KEY = "AAAAV42gvFo:.....";
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("purchases_cart");
function listenForNotificationRequests() {
// Attach an asynchronous callback to read the data at our posts reference
ref.on("child_added", function(snapshot, prevChildKey) {
var newPost = snapshot.val();
console.log("Uid: " + newPost.Uid);
console.log("fcmToken: " + newPost.fcmToken);
console.log("purchaseID: " + snapshot.key);
sendNotificationToUser(
newPost.fcmToken,
snapshot.key,
newPost.Uid,
function() {
snapshot.ref.remove();
}
);
});
}
function sendNotificationToUser(fcmToken, message, uid, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
"title": message,
"body": "some text for body notification",
"sound" : "default"
},
data:{
"prov_Uid" : uid,
"type": "new_sale",
"sale_ID": message
},
"to" : fcmToken,
"priority": "high",
"time_to_live" : 3600
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
在android中我的MessageReceived实现如下:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyGcmListenerService";
private String message_id = "";
private String type = "";
@Override
public void onMessageReceived(RemoteMessage message) {
String sale_id = "";
Object obj = message.getData().get("sale_ID");
if (obj != null) {
sale_id = obj.toString();
}
String message_type = "";
obj = message.getData().get("type");
if (obj != null) {
message_type = obj.toString();
}
SharedPreferences sharedPref = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
message_id = sharedPref.getString("sales_uuid","-");
type = sharedPref.getString("message_type","-");
if (!(message_id.equals(sale_id) && type.equals(message_type))) {
//String image = message.getNotification().getIcon();
String title = message.getNotification().getTitle();
if (title == null){
title = "title notification";
}
String text = message.getNotification().getBody();
if (text == null){
text = "body text";
}
String sound = message.getNotification().getSound();
String prov_uid = "";
obj = message.getData().get("prov_Uid");
if (obj != null) {
prov_uid = obj.toString();
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("sales_uuid",sale_id);
editor.putString("message_type",message_type);
editor.commit();
this.sendNotification(new NotificationData(0, title, text, sound));
}
}
/**
* Create and show a simple notification containing the received GCM message.
*
* @param notificationData GCM message received.
*/
private void sendNotification(NotificationData notificationData) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(NotificationData.TEXT, notificationData.getTextMessage());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = null;
try {
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(URLDecoder.decode(notificationData.getTitle(), "UTF-8"))
.setContentText(URLDecoder.decode(notificationData.getTextMessage(), "UTF-8"))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (notificationBuilder != null) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationData.getId(), notificationBuilder.build());
} else {
Log.d(TAG, "Não foi possível criar objeto notificationBuilder");
}
}
}
先谢谢你的帮助。