如何在应用关闭时发送通知?

时间:2017-01-12 20:21:31

标签: android firebase firebase-realtime-database android-service android-notifications

每当从firebase数据库添加子项时,我都希望发生通知。我在应用程序运行时或在后台运行时在onChildAdded()中运行以下代码,但显然不是在它关闭时。我读了一些关于启动服务的内容,但有点不知所措。

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 个答案:

答案 0 :(得分:1)

如果应用已关闭,则可能会关闭与数据库的连接。如果要将消息发送到处于该状态的应用,则应查看Firebase Cloud Massaging

此示例(结合Firebase实时数据库和Firebase云消息传递)可以在此博客文章中找到:Sending notifications between Android devices with Firebase Database and Cloud Messaging