[当应用未运行时处理whatsapp,twitter,facebook,instagram等的android推送通知

问题描述 投票:1回答:1

我正在开发类似whatsapp的聊天应用程序。当应用程序运行时,我使用websocket连接来处理两个用户之间的聊天,但是当应用程序被终止或未运行时,我尝试使用FCM推送通知服务来通知用户何时收到消息,就像whatsapp的方式一样做。

现在的问题是,当应用程序在前台或后台(从视图中遮挡,但仍在最近的任务菜单中)时,FCM会收到推送通知,一旦应用程序从最近的任务菜单中滑出或未启动完全没有收到通知。

[我已经在这里待了整整一个星期,我已经搜索并阅读了有关github,stackoverflow,quora和一些博客文章的各种文章和社区对话,但是我还没有找到可行的方法。

[我试图使用后台服务来保持与服务器连接的websocket连接,但是当应用程序不在前台时,由于Android杀死了后台服务,因此我无法使该服务继续运行。

[我的意思是类似whatsapp,twitter,instagram,facebook,gmail,likee,tiktok等的应用如何处理推送通知,使得即使该应用已关闭(从最近的菜单中滑出或根本没有启动),它仍会通知用户服务器上的一些更新。

这是我的代码...在服务器上

const firebase_admin = require('firebase-admin');
var service_account = require('./service_account.json');
firebase_admin.initializeApp({
    credential: firebase_admin.credential.cert(service_account),
    databaseURL: 'https://fcm_pushnotification-b9983.firebaseio.com/'
});

app.get('/sendPushNotification', (req, res) => {
    // This registration token comes from the client FCM SDKs.
    var registrationToken = 'clIilmqTRYarMF4gcrpEeH:APA91bFjkmZP7gU836ZCAzyPZaOWU4nU4SLL5OPWNkgukt0zBe0zvn5PEQ-42g60R5UXFN0tXQISjCDcbl032j2Tc81_OZ5uAJ7Aq3_OAaIz7g56oT547LnB9wiiBIKRZhc1TWGMP7lr';

    var message = {
        notification: {
            title: 'Samuel',
            body: 'This is an urgent message!',
        },
        webpush:{
            headers:{
                Urgency:'high'
            }
        },
        android:{
            priority:'high'
        },
        token: registrationToken
    };


    // Send a message to the device corresponding to the provided
    // registration token.
    firebase_admin.messaging().send(message)
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
        res.send('Successfully sent message:- '+ response);
      })
      .catch((error) => {
        console.log('Error sending message:- ', error);
        res.send('Error sending message:'+ error);
      });
});

Android上的我的服务类

public class MyFirebaseMessagingService extends FirebaseMessagingService{
    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    @Override
    public void onNewToken(@NonNull String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(token);
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        String title = remoteMessage.getNotification().getTitle();
        String body = remoteMessage.getNotification().getBody();
        this.sendNotification(new Notification(null, title, body, 0));
    }

    private void sendNotification(Notification notification){
    // Notification channel and notification is build here.
    }

}

清单

<uses-permission android:name="android.permission.INTERNET" />

        <service
            android:name=".Services.MyFirebaseMessagingService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

 <!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_heart" />
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
             notification message. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/red" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/notification_channel_id" />

当应用未运行时,是否需要我的权限才能工作?正如我所看到的,我什至在服务器上将通知优先级设置为高。我对此感到沮丧。欢迎任何帮助。

android firebase push-notification firebase-cloud-messaging background-service
1个回答
0
投票

问题是您正在发送fcm数据通知,但是在android端,您具有正常通知的代码。

在onMessageReceived方法中进行以下更改

Map<String, String> data = remoteMessage.getData().get("data");
String title = data.getOrDefault("title", "");
String body = data.getOrDefault("body", "");

传递此标题和正文字符串值以显示用于设置标题和消息文本的通知块代码

© www.soinside.com 2019 - 2024. All rights reserved.