0

我正在使用 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);
    }
}
4

1 回答 1

1

当应用处于非活动状态时,无法可靠地保持与 Firebase 数据库的连接。操作系统会主动防范此类进程,因为它们会影响电池寿命。

完成相同用例的正常方法是:

  1. 使用服务器端进程来检测数据库更改,
  2. 然后使用 Firebase Cloud Messaging 向应用发送消息,
  3. 根据收到的消息向用户显示通知或其他警报,
  4. 最后:如果用户根据通知启动应用程序,则重新连接到数据库。

有关这方面的示例,请参阅 Firebase 文档中有关在发生有趣事情时通知用户的文档,该文档使用 Cloud Functions 作为服务器端进程。

另请参阅这些类似的问题:

于 2021-06-20T14:27:30.820 回答