How to send a notification when the app is closed?

感情迁移 提交于 2019-12-11 07:59:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!