簡體   English   中英

當應用程序處於前台時發送推送通知

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

即使應用程序在后台,如何發送推送通知? 我有一個Android應用程序,它從服務器接收推送通知,並且當應用程序在后台時它不會發送。 僅在應用程序處於后台時發送。

您需要將其添加到清單文件中:

    <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>

這是刷新令牌的類(實例服務)

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

 }

消息服務,您將在其中接收消息/通知

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


    }
}
}

注意:不要忘記在項目的應用程序文件夾中添加google-service.json文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM