Java 如果应用程序在后台,如何使用fcm从服务器发送数据?
我正在从服务器向我的应用发送fcm通知 我正在从包含用户id的服务器发送数据。如果应用程序位于前台,我将在FirebaseMessageService类中获取此用户id。但当应用程序处于后台时,无法获取它。因为FirebaseMessagingService类仅在应用程序位于前台时才能执行 那么,当应用程序处于后台时,我如何获取此idJava 如果应用程序在后台,如何使用fcm从服务器发送数据?,java,android,firebase,background,firebase-cloud-messaging,Java,Android,Firebase,Background,Firebase Cloud Messaging,我正在从服务器向我的应用发送fcm通知 我正在从包含用户id的服务器发送数据。如果应用程序位于前台,我将在FirebaseMessageService类中获取此用户id。但当应用程序处于后台时,无法获取它。因为FirebaseMessagingService类仅在应用程序位于前台时才能执行 那么,当应用程序处于后台时,我如何获取此id public class MyFirebaseMessagingService extends FirebaseMessagingService {
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());
}
}
编辑:
我使用的数据负载仍然在MessageReceived上,当应用程序在后台时,不会被调用
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);
}
有人能帮忙吗?谢谢..在清单中注册您的服务
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
我明白了。在您的有效载荷中,您同时使用了
通知
和数据
有效载荷,当应用程序处于后台时,这会改变您应该接收详细信息的位置。在我在评论中提到的示例中,您可以在摘要中看到有效负载中是否包括这两个方面:
数据:在额外的意图
更具体地说:
在后台应用程序中处理通知消息
当你的应用程序在后台时,Android会将通知消息定向到系统托盘。默认情况下,用户点击通知会打开应用程序启动器
这包括同时包含通知和数据有效负载的消息(以及从通知控制台发送的所有消息)。在这些情况下,通知将发送到设备的系统托盘,数据有效载荷将在启动器活动的目的之外发送。
我认为@ArthurThompson的这篇文章很好地解释了这一点:
当您发送一条带有数据有效负载(通知和数据)的通知消息,并且应用程序位于后台时,您可以从用户点击通知后启动的其他意图中检索数据
点击通知时,从启动MainActivity的:
那么应该在哪个类中添加checkkAppIsRunningForeground方法?@Ganesh Pokaleyou可以在MyFirebaseMessagingService中添加该类,但是MyFirebaseMessagingService当应用程序位于后台时,该类不会被称为na?我已经在清单中注册了服务。当应用程序位于前台时会调用它,但当应用程序位于后台时不会调用它。@Ganesh PokaleOk,将你的应用程序置于后台,从服务器发送一条消息,并在此处添加stacktrace(如果你只使用
数据
有效负载),可以肯定的是,无论应用程序是在前台还是后台,它都只能在onMessageReceived
中接收。请参见“请检查已编辑的问题”@对不起,我没有得到什么可以解决的办法@艾尔。
public static boolean CheckAppIsRunningForground(Context mcontext) {
ActivityManager am = (ActivityManager) mcontext
.getSystemService(mcontext.ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equalsIgnoreCase(<YOUR PACKAGE>)) {
return true;
} else {
return false;
}
}
Boolean IsForground = CheckAppIsRunningForground(AgentService.this);
if (IsForground) {
//App is FourGround
} else {
sendNotification(remoteMessage.getNotification().getBody(),clickAction,title);
}
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}