我正在使用 Firebase 数据库制作应用程序。我的应用程序最重要的功能之一是显示数据的每日通知取决于 firebase 中的数据。它仅在应用程序打开时才有效,但即使应用程序被杀死,我也想让它工作。我怎样才能做到?这是我的代码:
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) {
}
});
}
}
这是运行广播接收器的函数
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);
}
}