当管理员从控制面板激活用户帐户时,我的应用程序收到 FCM 通知,我想通过 Toast 等方法执行一些操作,或者当用户单击推送通知时从我的数据库中删除一些数据。!
这可能吗?
这是 FirebaseMessagingService
类中的代码
public class CustomFirebaseMessagingService extends FirebaseMessagingService {
public static String INTENT_FILTER = "INTENT_FILTER";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
if (remoteMessage.getNotification() != null) {
Intent intent = new Intent(INTENT_FILTER);
sendNotification(remoteMessage.getNotification().getBody(), intent);
sendBroadcast(intent);
}
} catch (Exception ex) {
}
}
private void sendNotification(String messageBody, Intent intent) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("UPDATE")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
最佳答案
要使您的应用程序在后台时可单击通知,您需要 click_action
通知负载中的属性。这与 FirebaseMessagingService
完全分开。和其他此类,因为这些类在应用程序位于前台时起作用。
请检查此section Firebase 文档。
此外,当您定义 click_action
时属性,您还需要相应的 <action>
<intent-filter>
中的属性您希望启动的 Activity 的名称。
这个video非常详细地解释了它。
不过,请注意,您无法设置 click__action
属性(如果您从 Firebase 控制台发送通知)。仅当您从自己的管理服务器或使用 Firebase Cloud Functions 发送通知时才能执行此操作。
最后,在启动的 Activity 中,您可以额外设置 Data
使用数据属性(也显示在我上面链接的同一文档中)。当您通过单击通知启动应用程序时,您可以使用 getIntent()
获取通知数据。 。查看this answer有关如何执行此操作的更多详细信息。
它确实非常简单和优雅。
更新
例如,如果您的通知负载具有以下结构,
payload = {
notification: {
title: `You ordered a new product`,
click_action : 'HANDLE_NOTIFICATION',
},
data : {
product_id : 'ABC98292',
type : `Clothes`,
product_name : 'Cotton spring shirt'
}
};
然后,将过滤器放入您要在单击通知时打开的 Activity 的标记中。示例如下:-
<intent-filter>
<action android:name="HANDLE_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
然后您可以使用getIntent().getStringsExtra("product_id")
从通知中获取product_id等等。
这样,您将打开所需的 Activity ,并可以使用从通知中获得的相关详细信息填充该 Activity 。
关于java - 点击推送通知时如何做一些逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45078621/