简体   繁体   English

当应用程序处于前台时发送推送通知

[英]Push notification is sent when app is in foreground

How do I send a push a notification, even when the app is in the background? 即使应用程序在后台,如何发送推送通知? I have an android app that recieves push notifications from a server and it does not send when the app is in the background. 我有一个Android应用程序,它从服务器接收推送通知,并且当应用程序在后台时它不会发送。 it only sends when the app is in the background. 仅在应用程序处于后台时发送。

You need to add this in your manifest file: 您需要将其添加到清单文件中:

    <service
        android:name=".name_of_your_firebase_instace_service"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <service
        android:name=".nname_of_your_firebase_messaging_service
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

This is the class for refreshing token(instance service) 这是刷新令牌的类(实例服务)

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();




    // sending reg id to your server
    sendRegistrationToServer(refreshedToken);

    Log.d("NewToken",refreshedToken);

}

private void sendRegistrationToServer(final String token) {
    // sending gcm token to server
    Log.e(TAG, "sendRegistrationToServer: " + token);
}

 }

Mmessage service where you will receive your message/notification 消息服务,您将在其中接收消息/通知

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

private NotificationUtils notificationUtils;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.


    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
        //you can send your own custom notification here if you are sending notification in data tag or if you are sending notification with "notification tag" it will handle it automatically


    }
}
}

Note: do not forget to add your google-service.json file in app folder of your project 注意:不要忘记在项目的应用程序文件夹中添加google-service.json文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM