Question

I want to add to my application a new future, which shows, in a textView, the days left till a specific day, day setted by me, and the textView to be changed after every day passes. I tried a lot of things, a serched more than a lot, but nothing so far.

I started from here:

CountDownTimer countDown = new CountDownTimer(3000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

        }
    };
    countDown.start();

Thanks a lot !!!

Was it helpful?

Solution

Well, I did something similar a long time ago for a widget so just check out the code below and let me know if there's anything unclear. It might not be 100% "proper" since it was at the time when I was starting to code for Android but it should give you an idea...

    private static final long MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
    private static final long MILLIS_IN_HOUR = 60 * 60 * 1000;
    // ...


    Time awaitedTime = new Time();
    awaitedTime.set(second, minute, hour, day, month, year);

    Time defaultTime = new Time();
    defaultTime.set(0, 0, 0, 1, 7, 1989);

    if (awaitedTime.toMillis(false) == defaultTime.toMillis(false)) {

        return "No date";
    }
    else {

        int tempRest = 0;

        Time currentTime = new Time();
        currentTime.setToNow();

        long remainingTime = awaitedTime.toMillis(false) - currentTime.toMillis(false);
        int remainingDays = (int) (remainingTime / MILLIS_IN_DAY);

        tempRest = (int) (remainingTime % MILLIS_IN_DAY);
        int remainingHours = (int) (tempRest / MILLIS_IN_HOUR);

        // return YOUR STRING HERE
    }

OTHER TIPS

I just don't know how to show the days number, I could only show the date till the countdown will have to count. There is the problem, how to show the number of days?

I suggest you to use JodaTime.

Days.daysBetween(new LocalDate(start), new LocalDate(end)).getDays() 

About update:

Wy don't you just update the remaining days in onResume(). Do you really want to cover that case, when the user uses you app midnight?:)

If that is the case, you can use AlarmManager. Here is a draft:

AlarmManager manager = Context.getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, UpdateDaysReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

manager.setRepeating (int type, long triggerAtMillis, 24*60*60*1000, pi)

You can handle the update in the UpdateDaysReceiver.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top