关闭应用程序后如何发送通知?

问题描述:

我希望每当从我的Firebase数据库添加一个孩子时都发生通知.在应用运行或在后台运行时,我在onChildAdded()中运行以下代码,但显然在关闭时却没有.我读了一些有关启动服务的信息,但有点不知所措.

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());

如果该应用程序已关闭,则您与数据库的连接可能已关闭.如果您要向处于该状态的应用程序传递消息,则应查看 Firebase云按摩.

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.

此示例(结合Firebase实时数据库和Firebase云消息传递)可在以下博客文章中找到:

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.