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