i和其他用户未收到通知,尽管控制台表示成功。每当发表新文章时,我都想通知所有用户。因此,每当已发布的节点中有一个新密钥时,应触发FCM函数。
这是我的FCM函数:
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/published/{msg_id}').onWrite(event => {
const snapshot = event.data;
// Only send a notification when a new message has been created.
if (snapshot.previous.val()) {
return;
}
const msg_id = event.params.msg_id;
const msg_val=admin.database().ref(`messages/${msg_id}`).once('value');
return msg_val.then(msgResult =>{
const msg_title=msgResult.val().title;
const user_id=msgResult.val().userId;
console.log('msg title is',msg_title);
console.log('We have a new article : ', msg_id);
const payload={
data : {
title:"New Article",
body: msg_title,
msgid : msg_id,
userid : user_id
}
};
const getDeviceTokensPromise = admin.database().ref('/FCMToken').once('value');
return Promise.all([getDeviceTokensPromise, msg_title]).then(results => {
const tokensSnapshot = results[0];
const msgi = results[1];
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
console.log("tokenslist",tokensSnapshot.val());
const tokens= Object.keys(tokensSnapshot.val()).map(e => tokensSnapshot.val()[e]);
//var values = Object.keys(o).map(e => obj[e])]
const keyLists = Object.keys(tokensSnapshot.val());
console.log("keyList",keyLists[0]);
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {
const kk=tokensSnapshot.ref.child(keyLists[index]);
console.log("deleted is",kk);
tokensToRemove.push(tokensSnapshot.ref.child(keyLists[index]).remove());
// tokensToRemove.push(tokensSnapshot.ref.child((tokensSnapshot.child(tokens[index]).key).remove()));
}
// Cleanup the tokens who are not registered anymore.
}
else
{
console.log("Successful sent to",tokens[index]);
}
});
return Promise.all(tokensToRemove);
});
});
});
});
This is my FirebaseMessagingService :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notificatication_type = remoteMessage.getData().get("title");
Log.d("getnot",notificatication_type);
String msgTitle = remoteMessage.getData().get("body");
String user = remoteMessage.getData().get("userName");
String teller=remoteMessage.getData().get("userteller");
String photoloader=remoteMessage.getData().get("photoid");
String notification_body;
String notification_title=null;
if (user != null) {
notification_body = "New " + notificatication_type + " on your article " + msgTitle + " by " + user;
notification_title = "New" + notificatication_type;
} else {
if(teller!=null)
{
notification_body = notificatication_type + " " + msgTitle;
notification_title="New Audio";
}
else if(photoloader!=null)
{
notification_body = notificatication_type + " " + msgTitle;
notification_title = "New Photo";
}
else {
notification_body = notificatication_type + " " + msgTitle;
notification_title = "New Article";
}
}
// Log.d("notification_body", notification_body);
//TODO new article notification
// String click_action = remoteMessage.getNotification().getClickAction();
String mid = remoteMessage.getData().get("msgid");
Log.d("checkmid",mid);
String uid;
if(teller!=null)
{
uid = remoteMessage.getData().get("userteller");
}
else if(photoloader!=null)
{
uid=remoteMessage.getData().get("photoid");
}
else
uid = remoteMessage.getData().get("userid");
Map<String, String> params = new HashMap<String, String>();
//params = remoteMessage.getData().get("msgid"),remoteMessage.getData().get("userid");
params.put("msgid", mid);
params.put("userid", uid);
JSONObject object = new JSONObject(params);
// Log.d("JSON_OBJECT", object.toString());
//setBadge(getApplicationContext(), countNo, notification_body, object);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this,"sam")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_body)
.setAutoCancel(true);
//TODO CHANGED HERE INTENT
Intent resultIntent;
if(teller==null&&photoloader==null) {
resultIntent = new Intent(this, ArticleDetail.class);
resultIntent.setAction(Long.toString(System.currentTimeMillis()));
// Log.d("getAction",click_action);
resultIntent.putExtra("bkgnotification", object.toString());
}
else if(photoloader!=null)
{
resultIntent = new Intent(this, DisplayPhoto.class);
resultIntent.setAction(Long.toString(System.currentTimeMillis()));
// Log.d("getAction",click_action);
resultIntent.putExtra("bkgnotification", object.toString());
}
else
{
resultIntent = new Intent(this, PlayAudioActivity.class);
resultIntent.setAction(Long.toString(System.currentTimeMillis()));
// Log.d("getAction",click_action);
resultIntent.putExtra("bkgnotification", object.toString());
}
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
int mNotificationId = (int) System.currentTimeMillis();
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
mNotifyMgr.createNotificationChannel(channel);
}
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
// FirebaseDatabase db=FirebaseDatabase.getInstance();
// DatabaseReference dbref=db.getReference("notification");
//dbref.removeValue();
}
从日志中,我可以看到通知消息,有效载荷,数据收到。但是我没有收到通知的方式。我得到了此警告:
w/notification:使用流类型的使用被弃用用于操作其他 比音量控制04-29 01:32:53.970 5094-7881/com.samiapps.kv.roobaruduniya w/notification:请参阅 setSound((的文档用于使用 android.media.audioAttributes符合您的播放用例。
我的软件已更新为Oreo。
当我使用相同的通道ID" SAM"作为NotificationChannel的第一个参数