我正在尝试使用倒数计时器进行通知。 我做错了吗?
我尝试使用倒数计时器更新通知内的信息。 如果屏幕无法锁定,则它可以正常工作。但是在锁定的情况下,我的屏幕会打开每个通知(因此每秒)。因此,计时器可以正常工作,但是令人讨厌的是每一秒都使我的屏幕打开。
package com.example.yanec.schedulekpi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import com.example.yanec.schedulekpi.Activities.MainActivity;
import com.example.yanec.schedulekpi.Fragments.DetailScheduleInfoFragment;
public class ServiceShowNotification extends BroadcastReceiver {
CountDownTimer countDownTimer;
long timeLeft;
NotificationCompat.Builder mBuilder;
NotificationManagerCompat notificationManager;
@Override
public void onReceive(final Context context, final Intent intent) {
Log.d("myLogs", "OnReceive");
timeLeft = intent.getLongExtra(Constants.INTENT_PASS_DATE, 0);
showNotification(intent, context, Parser.toStringFrom(timeLeft));
countDownTimer = new CountDownTimer(timeLeft, Constants.COUNT_DOWN_INTERVAL) {
@Override
public void onTick(long millisUntilFinished) {
timeLeft -= Constants.COUNT_DOWN_INTERVAL;
mBuilder.setContentText(Parser.toStringFrom(timeLeft));
mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.notify(Constants.NOTIFICATION_ID, mBuilder.build());
}
@Override
public void onFinish() {
DetailScheduleInfoFragment.isServiceWorking = false;
}
};
countDownTimer.start();
}
private void showNotification(Intent intent, Context context, String time){
Intent intent1 = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, 0);
mBuilder = new NotificationCompat.Builder(context, Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_bar)
.setContentTitle(intent.getStringExtra(Constants.INTENT_PASS_NAME))
.setContentText(time)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(Constants.NOTIFICATION_ID, mBuilder.build());
}
}
如果我的屏幕已锁定并且正在更新通知,则我的屏幕不会唤醒。但是,如果我自己唤醒屏幕(不要仅使用唤醒按钮唤醒就解锁),它会向我显示更新的信息。谢谢。