我正在尝试显示一个倒计时的通知,直到CountDownTimer在服务中结束为止-并且工作正常,直到我将应用程序从“最近”菜单滑开。然后卡在其打开的第二个位置。
我正在使用startForeground()
。
我究竟做错了什么?在我的OnePlus 5t和Google像素模拟器上进行了测试。
public class PersistentNotificationService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showPersistentNotification();
return Service.START_STICKY;
}
void showPersistentNotification() {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "persistentNotification");
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
.setColor(Color.parseColor("#0097A7"))
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true)
.setVibrate(new long[0])
.setContentTitle("Time until period ends");
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
startForeground(0, builder.build());
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
builder.setContentText(millisUntilFinished / 1000 + " seconds until period ends");
notificationManager.notify(1, builder.build());
}
public void onFinish() {
showPersistentNotification();
}
}.start();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
答案 0 :(得分:0)
好吧,毕竟,唯一的问题是当我打电话给startForeground
时,我需要传递一个大于零的ID。
将此:startForeground(0, builder.build());
更改为:startForeground(1, builder.build());