请注意,FCM以不同的方式处理纯通知或数据负载的消息。请检查您发送的消息以查看其类型,并查阅Firebase文档。
当我有某个特定的Activity正在运行时,我不想收到通知。因此,我创建了一个静态实用程序类,它保留一个布尔属性,指示该Activity是否处于活动状态。在我的通知接收器中,我检查这个值并发出通知或不发出通知。就像这样:
我的静态实用程序类:
public class MyRunningActivity {
private static boolean isActivityRunning = false;
public static void setIsRunningActivity(boolean isRunning){
isActivityRunning = isRunning;
}
public static boolean getIsRunningActivity(){
return isActivityRunning;
}
}
在接收 onMessageReceived
的类中:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String notification = "";
String title = "";
if (remoteMessage.getData().size() > 0) {
title = getDataWithKey(remoteMessage.getData(), "title");
notification = getDataWithKey(remoteMessage.getData(), "body");
}
if (remoteMessage.getNotification() != null) {
notification = remoteMessage.getNotification().getBody();
title = remoteMessage.getNotification().getTitle();
}
sendNotification(title, notification);
}
private void sendNotification(String notificationTitle, String notificationBody) {
try{
Intent intent = new Intent(this, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NO_ANIMATION);
int requestCode = CodeGenerator.getRandomNumber(10, 10000);
PendingIntent pendingIntent = null;
try {
if(MyRunningActivityUtility.getIsRunningActivity()) {
intent.putExtra("add_ring_tone","true");
pendingIntent = PendingIntent.getActivity(this,
requestCode,
intent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
);
pendingIntent.send();
\\ !!! Notice that return here prevents the Notification from being sent !!!
return;
}
}
}
catch (Exception ex1){
Log.e(TAG, ex1.getMessage());
}
pendingIntent = PendingIntent.getActivity(this,
requestCode,
intent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (android.support.v7.app.NotificationCompat.Builder)
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.your_custom_icon)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int idNot = CodeGenerator.getRandomNumber(10, 10000);
notificationManager.notify(idNot, notificationBuilder.build());
}
catch (Exception ex){
Log.e(TAG, ex.getMessage());
}
}
这个例子中可能有一些你不需要的东西。