Firebase 使用 Node Js 函数通知在 android 中未接收,但它直接从 Firebase 面板工作



我正在尝试在安卓应用程序中实现通知。 我实现代码并直接从Firebase面板接收通知到我的Android设备中。 当我尝试使用节点JS方法时,它不起作用。 我正在安卓设备中使用第三方网络服务

下面的代码是我的节点JS函数代码。 请帮助我,我已经在许多网站上检查和搜索,但这种类型的问题没有根据,提前感谢

我已经在我的旧应用程序中实现了相同的代码并且工作正常,但是这些应用程序与Firebase完全连接。 但是这个当前的应用程序我正在使用Web服务。

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)

我在日志上收到函数"函数
执行耗时 501 毫秒,完成状态:"正常"的结果

方法getToken((已被弃用。您可以使用 getInstanceId(( 相反。

为了获取设备令牌并保存以供将来使用:

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

最新更新