Skip to content Skip to sidebar Skip to footer

Time Picker Performs Scheduled Task Every Minute Until Set Time Is Reached Instead Of Performing It Only At Set Time

I am using a Time Picker on which the user will set a time and then a toast message will be displayed at that time. The problem is that the toast is being displayed every minute un

Solution 1:

Try something like this, mHandler.removeMessages(0); will stop the hundler if it's already running, and the last one won't be stoped :

publicclassManualControlsFragmentextendsFragment {
    private TimePicker tp;
    private Calendar calendar;
    long pickedTimeInMillis;
    long timeDifference;
//some Fragment methodsHandlermHandler=newHandler(Looper.getMainLooper());

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Viewview= inflater.inflate(R.layout.fragment_manual_controls, container, false);
        tp = (TimePicker) view.findViewById(R.id.lightTimePickerStart);
        tp.setIs24HourView(true);
        calendar = Calendar.getInstance();
        tp.setOnTimeChangedListener(newTimePicker.OnTimeChangedListener() {
            @OverridepublicvoidonTimeChanged(TimePicker view, int hourOfDay, int minute) {
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
                calendar.set(Calendar.SECOND, 0);
                pickedTimeInMillis = calendar.getTimeInMillis();
                // at this point get the current timeCalendarcal= Calendar.getInstance();
                // now calculate the difference as the user actually selected a time
                timeDifference = pickedTimeInMillis - cal.getTimeInMillis();
                mHandler.removeMessages(0);
                mHandler.postDelayed(newRunnable() {
                    @Overridepublicvoidrun() {
                        //Do something here
                        Toast.makeText(getActivity().getApplicationContext(), "Bulb is now on", Toast.LENGTH_LONG).show();
                    }
                }, timeDifference);
            }
        });
        return view;
    }
}

Solution 2:

Per the TimePicker documentation, the listener does the following:

Set the callback that indicates the time has been adjusted by the user.

So I think your conclusion is correct by saying when the user scrolls through the timepicker it is repeatedly calling the callback defined in the listener.

Try getting the user defined time from TimePicker.getHour() and TimePicker.getMinute() and compare it to the current system time's minute and hour value every 30 seconds in a new thread. That should accomplish what you need.

Post a Comment for "Time Picker Performs Scheduled Task Every Minute Until Set Time Is Reached Instead Of Performing It Only At Set Time"