如何在 Android FirebaseMessagingService 中创建倒计时?

How to create a countdown inside Android FirebaseMessagingService?

我正在尝试像这样在 FirebaseMessagingService 中创建倒计时:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
CountDownTimer countDownTimer;
long timerLeft = 5000;

public void onMessageReceived(RemoteMessage remoteMessage) {
startTimer();
}

  public void startTimer() {

    countDownTimer = new CountDownTimer(timerLeft, 1000) {

        public void onTick(long millisUntilFinished) {
            timerLeft = millisUntilFinished;
            Log.d("timerleft: ",""+timerLeft);
        }
        public void onFinish() {

            timerLeft=10000;
        }
    }.start();
}

但是当我收到消息时出现以下错误:

java.lang.RuntimeException: Can't create handler inside thread Thread[Firebase-Messaging-Intent-Handle,5,main] that has not called Looper.prepare()

我该如何解决?

您始终可以在创建 new CountDownTimer 之前收听日志并调用 Looper.prepare(),但我建议您使用一些调度机制,例如WorkManagerAlarmManager。这取决于你想在计数器完成后实现什么

根据评论进行编辑:

public void onMessageReceived(RemoteMessage remoteMessage) {
    long lastMsgTimestamp = PreferenceManager.getDefaultSharedPreferences(this).
            getLong("lastMsgTimestamp", 0L);

    AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent pi = getPendingIntent(this);
    if(lastMsgTimestamp + 5000 >= System.currentTimeMillis()) {
        mgr.cancel(pi);
    }
    mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000, pi);

    PreferenceManager.getDefaultSharedPreferences(this).edit().
            putLong("lastMsgTimestamp", System.currentTimeMillis()).apply();
}

private static PendingIntent getPendingIntent(Context ctx){
    Intent i = new Intent(ctx, FiveSecsBroadcast.class);
    return PendingIntent.getBroadcast(ctx, 0, i, 0);
}

FiveSecsBroadcast 是一个 BroadcastReceiver,它将在 5 秒后触发(onReceive 方法)。您可以使用 Bundle extras in Intent

传递一些数据