I have used chronometer inside push notification using remote views and its working fine but once it reaches 00:00:00, it starts showing negative value like -01:00:00. I want to clear the notification in such case. For that I have used Handler which works fine when app is Background or foreground state, but when app is killed notification doesn't clear itself. Please let me know what can be done to solve this. Below is my code:
Chronometer Implementation :
if (!ends_at.isEmpty()){
Calendar end_calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date endDate = null;
try {
endDate = sdf.parse(ends_at);
end_calendar.setTime(endDate);
long startTime = SystemClock.elapsedRealtime();
Date now = new Date();
long elapsed = now.getTime() - end_calendar.getTimeInMillis();
long remainingTime = startTime - elapsed;
if(elapsed<0) {
expandedView.setChronometerCountDown(R.id.chronometer, true);
expandedView.setViewVisibility(R.id.timer_view, View.VISIBLE);
expandedView.setChronometer(R.id.chronometer, remainingTime, "%tH:%tM:%tS", true);
}
else{
expandedView.setViewVisibility(R.id.timer_view, View.GONE);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
for removing push :
if (!ends_at.isEmpty()) {
Calendar start_calendar = Calendar.getInstance();
Calendar end_calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date endDate;
try {
endDate = sdf.parse(ends_at);
assert endDate != null;
end_calendar.setTime(endDate);
long total_millis = (end_calendar.getTimeInMillis() - start_calendar.getTimeInMillis());
mHandler = new Handler(Looper.getMainLooper());
int finalM = m;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
notificationManager.cancel(finalM);
}
}, total_millis);
}
catch (ParseException e) { e.printStackTrace(); }
}
I was able to remove the notification by using - setTimeoutAfter(totalMilliSec) method with notification builder.