Push notification FCM does not run when the Fragment that contains it is not open

0

I have a Push notification code that is activated when one of the data in my Firebase Databade changes. The code works perfectly when I am inside the Fragment where it is incorporated, but when I close the app or change Fragment or Activity it stops working ...

What could be the problem? ... When I send notifications from the Firebase platform there are no problems, the notifications arrive even though the application is closed, but when I work with the code within this Fragment it is not the same , it only works as long as the application is open and it is in the Fragment that contains the code.

This is the code that is implemented and that executes the notification when a value changes in the Database

public void onDataChange(DataSnapshot dataSnapshot) {
                                                    Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
                                                    entries.clear();
                                                    while (items.hasNext()) {
                                                        DataSnapshot item = items.next();
                                                        log = (int) dataSnapshot.getChildrenCount();
                                                        txtlogactual.setText(log + "");

                                                        int aviso5 = Integer.parseInt(Numero5) - 5;
                                                        int aviso1 = Integer.parseInt(Numero5) - 1;

                                                        if (getActivity() != null) {

                                                            new TextoParpadeante(getActivity(), txtlogactual);

                                                            if (aviso5 == log) {
                                                                NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                                                                String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

                                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                                    @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);

                                                                    // Configure the notification channel.
                                                                    notificationChannel.setDescription("Channel description");
                                                                    notificationChannel.enableLights(true);
                                                                    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                                                                    notificationChannel.setLightColor(Color.RED);
                                                                    notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
                                                                    notificationChannel.enableVibration(true);
                                                                    notificationManager.createNotificationChannel(notificationChannel);
                                                                }

                                                                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getActivity(), NOTIFICATION_CHANNEL_ID);

                                                                notificationBuilder.setAutoCancel(true)
                                                                        .setDefaults(Notification.DEFAULT_ALL)
                                                                        .setWhen(System.currentTimeMillis())
                                                                        .setSmallIcon(R.drawable.alerta)
                                                                        .setTicker("Hearty365")
                                                                        .setPriority(Notification.PRIORITY_MAX)
                                                                        .setContentTitle("Aviso")
                                                                        .setContentText("¡Ingresa ahora!")
                                                                        .setContentInfo("Info");

                                                                notificationManager.notify(/*notification id*/1, notificationBuilder.build());
                                                            }

                                                            if (aviso1 == log) {
                                                                NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                                                                String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

                                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                                    @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);

                                                                    // Configure the notification channel.
                                                                    notificationChannel.setDescription("Channel description");
                                                                    notificationChannel.enableLights(true);
                                                                    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                                                                    notificationChannel.setLightColor(Color.RED);
                                                                    notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
                                                                    notificationChannel.enableVibration(true);
                                                                    notificationManager.createNotificationChannel(notificationChannel);
                                                                }

                                                                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getActivity(), NOTIFICATION_CHANNEL_ID);

                                                                notificationBuilder.setAutoCancel(true)
                                                                        .setDefaults(Notification.DEFAULT_ALL)
                                                                        .setWhen(System.currentTimeMillis())
                                                                        .setSmallIcon(R.drawable.alerta)
                                                                        .setTicker("Hearty365")
                                                                        .setPriority(Notification.PRIORITY_MAX)
                                                                        .setContentTitle("Aviso")
                                                                        .setContentText("¡Ingresa ahora!")
                                                                        .setContentInfo("Info");

                                                                notificationManager.notify(/*notification id*/1, notificationBuilder.build());
                                                            }

                                                        }

What could be the problem?

I hope you can help me, of course, thank you very much for your time and help!

    
asked by Matías Nicolás Núñez Rivas 16.08.2018 в 00:57
source

1 answer

2

When you refer to a push notification that is activated when you change something from firebase, and it does so only when your app is open, it is because it is not a push notification, but it is a local notification that you create with NotificationManager , a push notification is the one sent through the firebase console.

What is happening to you is that while you are in the Fragment, the listener that listens to your database remains active to warn the NotificationManager that you should create a notification when something changes in the database.

What you could do is use a background service that is listening to the change of your database and execute the NotificationManager to show you the notification. You can read a little more in this link

A snippet that you can use is the following to be able to do it

 public class ChildEventListener extends Service {
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            //Añadis el eventListener a firebase               
            Firebase myFirebaseRef = new Firebase("FirebaseURL");
            myFirebaseRef.child("REFERENCIA").addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    //llama a la creacion de las notificaciones aca
                }

                @Override
                public void onCancelled(FirebaseError error) {
                    Log.e("The read failed: ", error.getMessage());
                }
            });

          }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    Log.e("The read failed: ", firebaseError.getMessage());
                }
            });

            return START_STICKY;
       }

  }

remember to register the service in the manifest

 <service android:name=".ChildEventListener "/>

There are two reasons why the system can run a service. If someone calls Context.startService() , the system will recover the service (creating it and calling its method onCreate() if necessary) and then call its method onStartCommand(Intent, int, int) with the arguments supplied by the client.

For started services, there are two additional main modes of operation in which you can decide to execute, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as necessary.

Something to keep in mind is that if the system is running low on memory, it may be that the same Android OS kill you the service to save space and not be persuaded as a usable service.

    
answered by 16.08.2018 / 01:11
source