Java 从最近的应用程序中刷取应用程序后,倒数计时器在服务中不运行?
我试图显示一个倒计时通知,直到我的倒计时计时器在一个服务中结束,并且在我将我的应用程序从“最近”菜单中刷走之前,它工作正常。然后,它会在打开的第二秒卡住。 我正在使用Java 从最近的应用程序中刷取应用程序后,倒数计时器在服务中不运行?,java,android,service,background,countdowntimer,Java,Android,Service,Background,Countdowntimer,我试图显示一个倒计时通知,直到我的倒计时计时器在一个服务中结束,并且在我将我的应用程序从“最近”菜单中刷走之前,它工作正常。然后,它会在打开的第二秒卡住。 我正在使用startForeground()。 我做错了什么?在我的OnePlus 5t和谷歌像素模拟器上进行了测试 public class PersistentNotificationService extends Service { @Override public int onStartCommand(Intent
startForeground()
。
我做错了什么?在我的OnePlus 5t和谷歌像素模拟器上进行了测试
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;
}
}
好吧,毕竟,唯一的问题是,当我调用
startForeground
时,我需要传递一个高于零的ID
更改此项:
startForeground(0,builder.build())代码>到此:startForeground(1,builder.build())代码>使用Handler而不是CountDownTimer。@AbhayKoradiya CountDownTimer使用Handler-有什么区别?检查兄弟。@AbhayKoradiya我使用CountDownTimer的全部原因是因为它的onTick方法检查我的。