我已经让推送通知工作了,但现在我必须集成应用内通知。为了做到这一点,我做了以下事情:
在 gradle 文件中添加了 lib:
compile "com.facebook.android:notifications:${libs.fb_in_app_notifications}"
对我的主要活动进行了更改:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other non related code
NotificationsManager.presentCardFromNotification(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
NotificationsManager.presentCardFromNotification(this);
}
并调整了我已经存在的FirebaseMessagingService
以区分推送通知和应用内通知。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String PUSH_NOTIFICATION_EXTRA = "push";
private static final String NOTIFICATION_TITLE = "title";
private static final String NOTIFICATION_BODY = "body";
public MyFirebaseMessagingService() {
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Bundle data = new Bundle();
for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
data.putString(entry.getKey(), entry.getValue());
}
Timber.d("onMessageReceived");
if (NotificationsManager.canPresentCard(data)) {
Timber.d("canPresentCard -> in-app notification");
NotificationsManager.presentNotification(
this,
data,
new Intent(getApplicationContext(), MainActivity.class)
);
} else {
Timber.d("Can not present card -> push notification");
Context context = this.getApplicationContext();
Intent defaultAction = new Intent(context, MainActivity.class)
.setAction(Intent.ACTION_DEFAULT)
.putExtra(PUSH_NOTIFICATION_EXTRA, data);
String title = data.getString(NOTIFICATION_TITLE);
String body = data.getString(NOTIFICATION_BODY);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.launcher)
.setContentTitle(title == null ? "" : title)
.setContentText(body == null ? "" : body)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(
context,
0,
defaultAction,
PendingIntent.FLAG_UPDATE_CURRENT
));
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(123, mBuilder.build());
}
}
}
问题是该方法NotificationsManager.canPresentCard()
总是返回 false。任何线索为什么会发生这种情况?
编辑 1:该方法NotificationsManager.canPresentCard()
返回 false 因为RemoteMessage
它接收到的似乎不包含fb_push_card
它期望的 JSONObject 的键。