0

I'm making an app with Firebase database. One of the most important functionality of my app are daily notifications that are showing data depends on the data in firebase. It works only if app is on but I would like to make it work even if app is killed. How can I make it ? Here is my code :

public class WeekChallengeBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child(userID).child("CurrentChallenge");
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                int id = snapshot.child("numOfActiveChallenge").getValue(Integer.class);

                MyDBHandler myDBHandler = new MyDBHandler(context, null, null, MyDBHandler.DB_VERSION);

                int challengeWeek = id;

                Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                if (challengeWeek != 0) {
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(context, CHANNEL_1_ID)
                            .setSmallIcon(R.drawable.ic_stat_name)
                            .setContentTitle("Challenge for this week :")
                            .setContentText(myDBHandler.loadChallengeNotification(challengeWeek))
                            .setStyle(new NotificationCompat.BigTextStyle())
                            .setPriority(Notification.PRIORITY_MAX)
                            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                            .setAutoCancel(false);


                    v.vibrate(500);
                    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

                    notificationManager.notify(2, notification.build());
                } else
                    return;


            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

    }
}

Here is the function that run the broadcast receiver

public void MyAlarmWeekChallenge() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 12);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    if (calendar.getTime().compareTo((new Date())) < 0)
    {
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }

    Intent intent = new Intent(getApplicationContext(), WeekChallengeBroadcast.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    if(alarmManager != null){
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

There is no way to reliably keep a connection to the Firebase database while the app is not active. The operating system actively guards against such processes, as they affect battery life.

The normal way to accomplish the same use-case is to:

  1. use a server-side process to detect the database changes,
  2. then use Firebase Cloud Messaging to send a message to the app,
  3. display a notification or other alert to the user from the message received,
  4. and finally: reconnect to the database if the user starts the app based on the notification.

For an example of this, see the Firebase documentation on notifying users when something interesting happens, which uses Cloud Functions as the server-side process.

Also see these similar questions:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807