如果应用程序在后台,如何从服务器使用fcm发送数据? [英] How to get data sent from server using fcm if app is in background?

查看:162
本文介绍了如果应用程序在后台,如何从服务器使用fcm发送数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器发送fcm通知到我的应用程序。

我从包含user_id的服务器发送数据。如果应用程序处于前台,我将在FirebaseMessageService类中获取此用户标识。但是,当应用程序在后台没有得到它。由于FirebaseMessagingService类仅在应用程序处于前台时才能执行。



所以当应用程序在后台时,如何获得此ID?

  public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG =MyFirebaseMsgService;
private String mUserId;
私有布尔mUpdateNotification;

@Override
public void onMessageReceived(RemoteMessage remoteMessage){
//显示日志
中的数据//可选
Log.d(TAG ,From:+ remoteMessage.getFrom());
Log.d(TAG,Notification Message Body:+ remoteMessage.getNotification()。getBody());

String clickAction = remoteMessage.getNotification()。getClickAction();
$ b $ mUserId = remoteMessage.getData()。get(user_id);

String title = remoteMessage.getNotification()。getTitle();
$ b $ //调用方法来生成通知
sendNotification(remoteMessage.getNotification()。getBody(),clickAction,title);
}

//这个方法只产生推送通知
//和前面的帖子一样
private void sendNotification(String messageBody,String clickAction ,字符串标题){

mUpdateNotification = true;

Intent intent = new Intent(clickAction);

intent.putExtra(userId,mUserId);
intent.putExtra(updateNotification,mUpdateNotification);

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,
PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(0,notificationBuilder.build());




$ b

编辑:

我使用的数据有效载荷依然是onMessageReceived,当应用程序在后台时不会被调用。

  public function sendPush ($ text,$ tokens,$ apiKey,$ user_id)
{

$ notification = array(
title=>用户更新配置文件,
text=> $ text,
'vibrate'=> 3,
click_action=>OPEN_ACTIVITY_2,
sound=>default ,
'user_id'=> $ user_id
);

$ data = array(user_id=> $ user_id);
$ b $ msg = array

'message'=> $ text,
'title'=>'用户更新的配置文件',
'tickerText'=>'新消息',
);
$ fields = array

'to'=> $ tokens,
'data'=> $ data,
'notification'=> $通知
);

$ header = array

'Authorization:key ='。$ apiKey,
'Content-Type:application / json'
);

$ ch = curl_init();
curl_setopt($ ch,CURLOPT_URL,'https://android.googleapis.com/gcm/send');
curl_setopt($ ch,CURLOPT_POST,true);
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ headers);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ ch,CURLOPT_POSTFIELDS,json_encode($ fields));

$ result = curl_exec($ ch);
// echo($ result);
//返回$ result;
curl_close($ ch);
}

任何人都可以帮忙吗?谢谢。

解决方案

我明白了。在你的载荷中,你使用通知数据有效载荷,在你应该接收细节的地方该应用程序是在后台。在评论中提到的文档中,您可以看到如果两者都包含在有效载荷中:


数据:用于附加的意图




更具体地说:


在后台应用程序中处理通知消息

这包括包含通知和数据有效负载的消息(以及所有发送的消息从通知控制台)。在这些情况下,通知被传送到设备的系统托盘,数据有效载荷是以您的启动程序Activity的意图的附加形式传递的。


我认为@ArthurThompson的回答很好地解释了这个问题:


当您发送带有数据有效载荷(通知和数据)的通知消息,并且应用程序在后台时,您可以从附件中获取数据这是因为用户点击通知而启动的意图。

FCM示例,当启动MainActivity的时候通知被点击:



  if(getIntent()。getExtras()!= null) {
(String key:getIntent()。getExtras()。keySet()){
String value = getIntent()。getExtras()。getString(key);
Log.d(TAG,Key:+ key +Value:+ value);
}
}


I am sending fcm notifications to my app from server.

I am sending data from server which contains user_id. I am getting this userId in FirebaseMessageService class if app is in foreground. But Not getting it when the app is in background. As FirebaseMessagingService class only gets execute when the app is in foreground.

So how can I get this id when the app is in background?

    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";
    private String mUserId;
    private Boolean mUpdateNotification;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        String clickAction = remoteMessage.getNotification().getClickAction();

        mUserId = remoteMessage.getData().get("user_id");

        String title = remoteMessage.getNotification().getTitle();

        //Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getBody(),clickAction,title);
    }

    //This method is only generating push notification
    //It is same as we did in earlier posts
    private void sendNotification(String messageBody,String clickAction,String title) {

        mUpdateNotification = true;

        Intent intent = new Intent(clickAction);

        intent.putExtra("userId",mUserId);
        intent.putExtra("updateNotification",mUpdateNotification);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}

EDIT:

I am using data payload still onMessageReceived dose not get called when app is in background.

 public function sendPush($text, $tokens, $apiKey,$user_id)
{

    $notification = array(
        "title" => "User updated profile.",
        "text" => $text,
        'vibrate' => 3,
        "click_action" => "OPEN_ACTIVITY_2",
        'sound' => "default",
        'user_id' => $user_id
    );

    $data = array("user_id" => $user_id);

    $msg = array
    (
        'message' => $text,
        'title' => 'User updated profile.',
        'tickerText' => 'New Message',
    );
    $fields = array
    (
        'to' => $tokens,
        'data' => $data,
        'notification' => $notification
    );

    $headers = array
    (
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    $result = curl_exec($ch);
    //  echo($result);
    //    return $result;
    curl_close($ch);
}

Can anyone help with this please? Thank you..

解决方案

I see. In your payload you are using both notification and data payload, which changes where you're supposed to receive the details when the app is in background. In the doc I mentioned in the comments, you can see in the summary if both are included in the payload:

Data: in extras of the intent.

More specifically:

Handle notification messages in a backgrounded app

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.

This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

I think this answer by @ArthurThompson explains it very well:

When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.

From the FCM sample which launches the MainActivity when the notification is tapped:

if (getIntent().getExtras() != null) {
    for (String key : getIntent().getExtras().keySet()) {
        String value = getIntent().getExtras().getString(key);
        Log.d(TAG, "Key: " + key + " Value: " + value);
    }
}

这篇关于如果应用程序在后台,如何从服务器使用fcm发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆