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

Posted

技术标签:

【中文标题】Firebase 使用 Node Js 功能通知未在 android 中接收,但它直接从 firebase 面板工作【英文标题】:Firebase using Node Js function notification not receiving in android but it work directly from firebase panel 【发布时间】:2020-01-09 11:05:35 【问题描述】:

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

下面的代码是我的节点 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)


我在日志中收到函数的这个结果 "函数执行耗时 501 毫秒,完成状态为:'ok'"

【问题讨论】:

你能给你提供接收通知的App类吗?它应该继承自 FirebaseMessagingService @RanderGabriel 我更新了代码,请检查并帮助我,谢谢 【参考方案1】:

方法 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);
        );


【讨论】:

我尝试了这段代码,结果是成功,但问题还是一样。可能是 java 代码问题,我更新了有问题的代码并添加了 java 代码,请检查并帮助我,感谢您的回答 您在注册设备令牌吗? 我在我的代码中添加了另外两个代码,我如何编写 MyFirebaseInstanceIDService 类以获取令牌,其次如何使用令牌将数据发送到 firebase 我已经更新了我的答案。 getToken() 已弃用。使用我在代码中显示的 getInstanceId()。

以上是关于Firebase 使用 Node Js 功能通知未在 android 中接收,但它直接从 firebase 面板工作的主要内容,如果未能解决你的问题,请参考以下文章