Firebase 使用 Node Js 函数通知未在 android 中收到,但它直接从 firebase 面板工作
Firebase using Node Js function notification not receiving in android but it work directly from firebase panel
我正在尝试在 android 应用中实现通知。我直接从 Firebase 面板实现代码并将通知接收到我的 android 设备中。当我尝试使用节点 js 方法时,它不起作用。我在 android 设备中使用第三方网络服务
下面的代码是我的node js函数代码。
请帮助我,我已经在许多站点上进行了检查和搜索,但是没有发现此类问题,在此先感谢
同样的代码我已经在我的旧应用程序中实现并且工作正常但是那些应用程序与 firebase 完全连接。但是我当前使用的是网络服务。
const functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("./xxxxxxx-xxxxx-firebase-adminsdk-xxxxx-xxxxxxxxxx.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxxxx-xxxxx.firebaseio.com"
});
//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{
const id=context.params.first_id;
const data2=snapshot.val()
var token=data2.Token
var text= data2.Name
// Send a message to the device corresponding to the provided
// registration token.
return Promise.all([token,text]).then(results =>{
var payload = {
data:{
username: "name",
usertoken: token,
notificationTitle: "name1",
notificationMessage: "ntest"
}
};
return admin.messaging().sendToDevice(token, payload)
})
})
<!-- Notification Services Manifest file-->
<service
android:name=".FCM_Serivces.MyFirebaseNotificationService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/> <!-- Get Notification -->
</intent-filter>
</service>
<service
android:name=".FCM_Serivces.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> <!-- Get Token Id -->
</intent-filter>
</service>
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
registerToken(token);
}
private void registerToken(String token) {
}
}
//Java Class
public class MyFirebaseNotificationService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
SendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
}
private void SendNotification(String title,String msg){
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 defaultSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(msg);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setSound(defaultSound);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
//Gradle
implementation 'com.google.firebase:firebase-database:16.0.4'
implementation 'com.google.firebase:firebase-functions:16.1.3'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'org.apache.httpcomponents:httpclient:4.5.8'
//i use this code in click lister for send data with token for notification
DatabaseReference referenceNotification =FirebaseDatabase.getInstance().getReference().child("Notifications").push();
Map<String,String> mMap=new HashMap<>();
mMap.put("Name","01");
mMap.put("Token", FirebaseInstanceId.getInstance().getToken());
mMap.put("Title","Test");
mMap.put("Message","1234");
referenceNotification.setValue(mMap)
我在日志中收到了这个函数的结果
"Function execution took 501 ms, finished with status: 'ok'"
The method getToken() is deprecated. You can use getInstanceId()
instead.
获取设备令牌并保存以供进一步使用:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
String newToken = instanceIdResult.getToken();
Log.e("newToken", newToken);
getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("myToken", newToken).apply();
});
保存到数据库时:
mMap.put("Token",
getActivity().getPreferences(Context.MODE_PRIVATE).getString("myToken", "empty :("));
现在使用令牌使用节点服务器发送通知:
//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{
const id=context.params.first_id;
const data2=snapshot.val()
var token=data2.Token
var text= data2.Name
var payload = {
data:{
username: "name",
usertoken: token,
notificationTitle: "name1",
notificationMessage: "ntest"
},
token: deviceRegistrationToken
};
admin.messaging().send(payload)
.then(() => {
console.log("success");
return null;
})
.catch(error => {
console.log(error);
});
}
我正在尝试在 android 应用中实现通知。我直接从 Firebase 面板实现代码并将通知接收到我的 android 设备中。当我尝试使用节点 js 方法时,它不起作用。我在 android 设备中使用第三方网络服务
下面的代码是我的node js函数代码。 请帮助我,我已经在许多站点上进行了检查和搜索,但是没有发现此类问题,在此先感谢
同样的代码我已经在我的旧应用程序中实现并且工作正常但是那些应用程序与 firebase 完全连接。但是我当前使用的是网络服务。
const functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("./xxxxxxx-xxxxx-firebase-adminsdk-xxxxx-xxxxxxxxxx.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxxxx-xxxxx.firebaseio.com"
});
//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{
const id=context.params.first_id;
const data2=snapshot.val()
var token=data2.Token
var text= data2.Name
// Send a message to the device corresponding to the provided
// registration token.
return Promise.all([token,text]).then(results =>{
var payload = {
data:{
username: "name",
usertoken: token,
notificationTitle: "name1",
notificationMessage: "ntest"
}
};
return admin.messaging().sendToDevice(token, payload)
})
})
<!-- Notification Services Manifest file-->
<service
android:name=".FCM_Serivces.MyFirebaseNotificationService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/> <!-- Get Notification -->
</intent-filter>
</service>
<service
android:name=".FCM_Serivces.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> <!-- Get Token Id -->
</intent-filter>
</service>
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
registerToken(token);
}
private void registerToken(String token) {
}
}
//Java Class
public class MyFirebaseNotificationService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
SendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
}
private void SendNotification(String title,String msg){
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 defaultSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(msg);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setSound(defaultSound);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
//Gradle
implementation 'com.google.firebase:firebase-database:16.0.4'
implementation 'com.google.firebase:firebase-functions:16.1.3'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'org.apache.httpcomponents:httpclient:4.5.8'
//i use this code in click lister for send data with token for notification
DatabaseReference referenceNotification =FirebaseDatabase.getInstance().getReference().child("Notifications").push();
Map<String,String> mMap=new HashMap<>();
mMap.put("Name","01");
mMap.put("Token", FirebaseInstanceId.getInstance().getToken());
mMap.put("Title","Test");
mMap.put("Message","1234");
referenceNotification.setValue(mMap)
我在日志中收到了这个函数的结果
"Function execution took 501 ms, finished with status: 'ok'"
The method getToken() is deprecated. You can use getInstanceId() instead.
获取设备令牌并保存以供进一步使用:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
String newToken = instanceIdResult.getToken();
Log.e("newToken", newToken);
getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("myToken", newToken).apply();
});
保存到数据库时:
mMap.put("Token",
getActivity().getPreferences(Context.MODE_PRIVATE).getString("myToken", "empty :("));
现在使用令牌使用节点服务器发送通知:
//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{
const id=context.params.first_id;
const data2=snapshot.val()
var token=data2.Token
var text= data2.Name
var payload = {
data:{
username: "name",
usertoken: token,
notificationTitle: "name1",
notificationMessage: "ntest"
},
token: deviceRegistrationToken
};
admin.messaging().send(payload)
.then(() => {
console.log("success");
return null;
})
.catch(error => {
console.log(error);
});
}