如果app在后台,如何使用fcm从服务器发送数据?

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

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

那么当应用程序处于后台时,如何获得此ID?

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

编辑:

我正在使用仍然onMessageReceived的数据有效负载当app在后台时不会被调用。

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

有人可以帮忙吗? 谢谢..

我懂了。 在您的有效负载中,您正在使用notificationdata有效负载,这会在应用程序处于后台时更改您应该接收详细信息的位置。 在我在评论中提到的文档中,您可以在摘要中看到两者是否包含在有效负载中:

数据:意图的额外内容。

进一步来说:

处理背景应用中的通知消息

当您的应用在后台时,Android会将通知消息定向到系统托盘。 用户点按通知会默认打开应用启动器。

这包括包含通知和数据有效负载的消息(以及从Notifications控制台发送的所有消息)。 在这些情况下,通知将传递到设备的系统托盘,并且数据有效负载将在启动器活动的附加内容中传递。

我认为@ArthurThompson的这个答案解释得非常好:

当您发送带有数据有效负载(通知和数据)的通知消息并且应用程序位于后台时,您可以从用户点击通知而启动的意图的附加内容中检索数据。

从点击通知时启动MainActivity的FCM示例 :

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

在清单中注册您的服务

            

你可以检查app是否在Foreground中

  public static boolean CheckAppIsRunningForground(Context mcontext) { ActivityManager am = (ActivityManager) mcontext .getSystemService(mcontext.ACTIVITY_SERVICE); // get the info from the currently running task List taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity; if (componentInfo.getPackageName().equalsIgnoreCase()) { return true; } else { return false; } } 

并在onMessageReceived添加此代码

  Boolean IsForground = CheckAppIsRunningForground(AgentService.this); if (IsForground) { //App is FourGround } else { sendNotification(remoteMessage.getNotification().getBody(),clickAction,title); }