这是我的舱单:
<service android:name=".fcm.PshycoFirebaseMessagingServices">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".fcm.PshycoFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
当应用程序在后台和通知到达,然后默认通知来,不运行我的onmessagerreceived代码。
这是我的onMessageReceived代码。如果我的应用程序在前台运行,而不是在后台运行,就会调用这个函数。我怎么能运行这段代码时,应用程序是在后台太?
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
data = remoteMessage.getData();
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
String imageUrl = (String) data.get("image");
String action = (String) data.get("action");
Log.i(TAG, "onMessageReceived: title : "+title);
Log.i(TAG, "onMessageReceived: message : "+message);
Log.i(TAG, "onMessageReceived: imageUrl : "+imageUrl);
Log.i(TAG, "onMessageReceived: action : "+action);
if (imageUrl == null) {
sendNotification(title,message,action);
} else {
new BigPictureNotification(this,title,message,imageUrl,action);
}
}
// [END receive_message]
我觉得所有的响应都是不完整的,但它们都有一些你需要处理的东西,当你的应用程序在后台时,一个有数据的通知。
遵循这些步骤,你将能够在应用程序处于后台时处理通知。
添加一个intent-filter,像这样:
<活动android: name = "。MainActivity”>
<意图过滤器>
<行动android: name = "。MainActivity " / >
<category android:name="android.intent.category. default " />
< /意图过滤器>
到要处理通知数据的活动。
以以下格式发送通知:
{
“通知”:{
"click_action": "。MainActivity”,
"body": "new Symulti update !",
"title": "新的Symulti更新!",
"icon": "ic_notif_symulti"},
"data":{…},
"to": "c9Vaa3ReGdk:APA91bH-AuXgg3lDN2WMcBrNhJZoFtYF9"}
这里的关键是加法
"click_action" : ".MainActivity"
其中. mainactivity是您在步骤1中添加的带有intent-filter的活动。
从.MainActivity的onCreate中的通知中获取数据信息:
onCreate(Bundle savedInstanceState)
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
//获取通知数据信息
Bundle Bundle = getIntent().getExtras();
If (bundle != null) {
//bundle必须包含通知的"data"字段发送的所有信息
}
}
这就是你需要做的。
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
}
不是每次调用它时,只有当应用程序是在前景
有一个覆盖方法,这个方法每次都会被调用,不管什么应用程序在前台,在后台或被杀死,但是这个方法在这个firebase API版本中可用
这是你必须从gradle导入的版本
compile 'com.google.firebase:firebase-messaging:10.2.1'
这就是方法
@Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
// you can get ur data here
//intent.getExtras().get("your_data_key")
}
在之前的firebase API中,这个方法是不存在的
当应用程序在后台....时,Fire base句柄本身现在你有了这个方法
无论你想做什么…你可以在这里用这个方法.....
如果您使用的是以前的版本,那么默认活动将启动
在这种情况下,你可以用同样的方法得到数据
if(getIntent().getExtras() != null && getIntent().getExtras().get("your_data_key") != null) {
String strNotificaiton = getIntent().getExtras().get("your_data_key").toString();
//做你想做的事....
}
通常这是我们在通知中从服务器获得的结构
{
"notification": {
"body": "Cool offers. Get them before expiring!",
"title": "Flat 80% discount",
"icon": "appicon",
"click_action": "activity name" //optional if required.....
},
"data": {
"product_id": 11,
"product_details": "details.....",
"other_info": "......."
}
}
这是由你决定的,你想给数据键或者你想给任何你可以给.......的通知
无论你在这里给出什么,用相同的键,你都会得到数据.........
有少数情况下,如果你没有发送点击动作在这种情况下,当你将点击通知默认活动将打开,但如果你想打开你的特定活动时,应用程序是在后台,你可以从这个handleIntent方法调用你的活动,因为这是每次调用
2023年1月
对于那些实现了最新的Firebase云消息(FCM)的应用程序,您可能不会被限制在后台或完全关闭的情况下分别为应用程序发送数据和通知以处理数据。正如这里的一些回答所解释的那样,简短的版本是:
在你的启动器活动上,监视启动时的额外内容;
测试您的FCM数据中的唯一键是否在列表中;
如果存在,获取必要的数据并调用您的活动来处理您想要做的处理。
//Firebase
// [START handle_data_extras]
if (getIntent().getExtras() != null) {
boolean fcmExtraFlag = false;
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
if(key.equalsIgnoreCase("tracerId")){
//test your known key to be sure it is from fcm
//this must have come from notification (system) tray
//this will come whether the app was in the background or completely off
//generally, this could be in the main activity as it has the intent-filter already set
fcmExtraFlag = true;
}
}
//pick fcm values if present and notify and/or process accordingly
//you may add time-lookup to ignore delayed (time-passed) ones; and ignore
if(fcmExtraFlag){
String tracerId = (String) getIntent().getExtras().get("tracerId");
//prepare your data as needed
String tracerData = tracerId+">"+data-one+">"+data-two;
String msgBody = "This is a test notification; data received: "+tracerId;
String fcmMessage = msgBody;
//start your confirmation activity, directly or whichever way
SidUtils.firebaseStartConfirms(msgBody, tracerData, this);
}
}
// [END handle_data_extras]
如前所述,如果可能的话,这应该在你的主活动中,以处理你的应用程序实际上关闭的情况-而不仅仅是在后台。这些将通过点击系统托盘上的应用程序通知来触发。
感谢你们所有人的回答。但是我通过发送数据消息而不是发送通知来解决这个问题。
服务器代码
<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "C-l6T_a7HouUK****";
$serverKey = "AAAAaOcKS00:********";
define( 'API_ACCESS_KEY', $serverKey );
$registrationIds = array($token);
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text
here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'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 );
curl_close( $ch );
echo $result;
?>
并在onmessagerreceived中捕获数据
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("message"));
}
// Check if message contains a notification payload.
else if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Notify.class).putExtra("msg",messageBody);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "idddd";
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(MyFirebaseMessagingService.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
此情况仅用于firebase管理通知
如果应用程序在后台,则不会触发FirebaseMessagingService
要处理这种情况,请转到launcher activity,检查附加的intent bundle,并使用以下代码打印出所有数据:
intent?.extras?.let {it->
for (key in bundle.keySet()) {
val value = bundle[key]
Log.d("NotificationData", String.format("%s %s (%s)", key, value.toString(), value!!.javaClass.name))
}
}
显示所有数据类型的签入日志;
例子:
我想从通知中获得周和标题将使用这段代码
intent?.extras?.let {it->
if (it.containsKey("week")){
}
if (it.containsKey("title")){
}