问题
I want a notification to happen whenever a child is added from my firebase database. I have the below code working within onChildAdded() while the app is running or in the background, but obviously not when it's closed. I read something about starting a service but was a bit overwhelmed.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mRecyclerView.getContext())
.setSmallIcon(R.drawable.icon)
.setContentTitle("Title")
.setContentText("Content Text");
Intent newAnimalIntent = new Intent(mRecyclerView.getContext(), MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mRecyclerView.getContext());
stackBuilder.addNextIntent(newAnimalIntent);
PendingIntent newAnimalPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(newAnimalPendingIntent);
NotificationManager NM = (NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);
NM.notify(0,mBuilder.build());
回答1:
If the app is closed, your connection to the database may be closed, If you want to deliver messages to an app in that state, you should look at Firebase Cloud Massaging.
An example of this (combining the Firebase Realtime Database and Firebase Cloud Messaging) can be found in this blog post: Sending notifications between Android devices with Firebase Database and Cloud Messaging.
来源:https://stackoverflow.com/questions/41622275/how-to-send-a-notification-when-the-app-is-closed