I am trying to show a notification to count down the seconds until my CountDownTimer ends within a service - and works ok until I swipe my app away from the recents menu. It then gets stuck on the second that it is on. I am using startForeground()
. What am I doing wrong? Tested on both my OnePlus 5t and the Google pixel emulator.
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;
}
}
Ok, so after all, the only issue was the fact that I needed to pass an ID above zero when I call startForeground
.
Changed this: startForeground(0, builder.build());
to this: startForeground(1, builder.build());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.