Search code examples
androidandroid-handler

Implementing Handlers the basic way


I have this sample application on handlers which fires a Log at a certain time, but its seems to be not working when i clicked my start button. Below is my code.

public class Main extends Activity {
    private long selectedTimeInMills;
    private Handler handler;
    private static final Calendar CALENDAR = Calendar.getInstance();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TimePicker timepicker = (TimePicker) findViewById(R.id.timePicker1);
        final TextView timeText = (TextView) findViewById(R.id.time);

        Button start = (Button) findViewById(R.id.button1);
        handler = new Handler();
        String textTime = formatDate(CALENDAR.getTimeInMillis(), "hh:mm a");
        timeText.setText(textTime);

        timepicker.setOnTimeChangedListener(new OnTimeChangedListener() {

            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                CALENDAR.set(Calendar.HOUR_OF_DAY, hourOfDay);
                CALENDAR.set(Calendar.MINUTE, minute);
                selectedTimeInMills = CALENDAR.getTimeInMillis();
                String textTime = formatDate(CALENDAR.getTimeInMillis(), "hh:mm a");
                timeText.setText(textTime);
            }
        });

        start.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Runnable runnable =  new Runnable() {

                    public void run() {
                        Log.d("HandlerCheck", "Handler Fired! @ ("+selectedTimeInMills+") "+formatDate(selectedTimeInMills, "hh:mm a"));
                    }
                };
                boolean flag = handler.postAtTime(runnable, selectedTimeInMills);

                Toast.makeText(Main.this, "Handler is Fired?:: "+flag, Toast.LENGTH_LONG).show();
            }


        });

    }
}

NOTE: When I clicked on my button and it implement the handler.postAtTime() it returns true but still it won't display the Log on DDMS even though i've set my timepicker 1 min from the current time still won't fire the Log message on DDMS


Solution

  • postAtTime method in Handler class takes in the time in milliseconds from the statup; not the Calendar time (which is what you are passing). You should be using SystemClock.uptimeMillis() to calculate the time instead.

    Alternatively, you can use postDelayed function to invoke the Runnable object after a set time period (in milliseconds).

    // Introduce a new private variable
    private long delayedTimeInMillis;
    
    // Update delayedTimeInMillis inside onTimeChanged method:
    delayedTimeInMillis = selectedTimeInMills - Calendar.getInstance().getTimeInMillis();
    
    // replace handler.postAtTime(runnable, selectedTimeInMills); line with this:
    handler.postDelayed(runnable, delayedTimeInMillis)