如何在Android应用程序的后台发送消息?

时间:2018-03-28 19:26:06

标签: android firebase push-notification firebase-cloud-messaging

我想创建一个可以向手机发送firebase推送消息的应用。这个现在有效。但是当我关闭应用程序时,我也希望获得与应用程序中相同的推送消息。

我搜索了很多但我无法找到解决方案。我找到了IntentService,但我不确定如何将其用于推送通知。

更新 我使用了firebase教程。我的服务类:

package com.example.kai.msgtest;

import android.app.NotificationManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        sendNotification(remoteMessage);
    }

    private void sendNotification(RemoteMessage remoteMessage) {
        Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_mail_white_18dp)
                .setContentTitle("Sie haben Post")
                .setSound(sound)
                .setContentText(remoteMessage.getData().get("message"));
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
    }
}

1 个答案:

答案 0 :(得分:0)

我使用fcm api解决了这个问题。我配置了一些像fcm消息中显示的图标,如下所示:

curl -X POST --header "Authorization: key=<serverkey>" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"to\":\"<device-token>\",\"notification\":{\"body\":\"test\", \"icon\":\"ic_mail_white_18dp\"},\"priority\":10}"

之后,图标显示为应用程序位于前台