Wednesday, 12 February 2014

Android DateTime receiver without using Broadcast Receiver

We usually use Date and Time listener to update Date & Time in our application. This can also be achieved using Runnable and Handler. Which is efficient and very accurate. It just requires the calculation of System Time and Current Time.

Below Snippet is used to update time based on Seconds.

Runnable runnable = new Runnable() {

    @Override
    public void run() {

        long date = System.currentTimeMillis(); 

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

        TextView txt = (TextView)findViewById(R.id.txt);
        txt.setText(sdf.format(date));

        handler.postDelayed(runnable, DateUtils.SECOND_IN_MILLIS - System.currentTimeMillis() % DateUtils.SECOND_IN_MILLIS);
    }
};

Similarly on Minute based

Runnable runnable = new Runnable() {

    @Override
    public void run() {

        long date = System.currentTimeMillis(); 

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

        TextView txt = (TextView)findViewById(R.id.txt);
        txt.setText(sdf.format(date));

        handler.postDelayed(runnable, DateUtils.MINUTE_IN_MILLIS - System.currentTimeMillis() % DateUtils.MINUTE_IN_MILLIS);
    }
};

 Similarly on Hourly Basis

Runnable runnable = new Runnable() {

    @Override
    public void run() {

        long date = System.currentTimeMillis(); 

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

        TextView txt = (TextView)findViewById(R.id.txt);
        txt.setText(sdf.format(date));

        handler.postDelayed(runnable, DateUtils.HOUR_IN_MILLIS - System.currentTimeMillis() % DateUtils.HOUR_IN_MILLIS);
    }
};


Similarly on Daily Basis, which is actually nobody uses. ROFL :D :D but still


Runnable runnable = new Runnable() {

    @Override
    public void run() {

        long date = System.currentTimeMillis(); 

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

        TextView txt = (TextView)findViewById(R.id.txt);
        txt.setText(sdf.format(date));

        handler.postDelayed(runnable, DateUtils.DAY_IN_MILLIS - System.currentTimeMillis() % DateUtils.DAY_IN_MILLIS);
    }
};

And so on. Enjoy coding.

No comments:

Post a Comment