Search code examples
androidtimepicker

Storing hour&minute values from TimePicker


I'm writing an App that get the hour/minute value from TimePicker, display them on the screen and set these values in AlarmManager to ring the alarm.

I can display the hour and minute on screen correctly, but I can't store them for using alarmManager. How can I do that?

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

static final int timePicker1 = 1;

//need to store values in here
static int aHour1, aMin1;

private int mChosenTime = 1;

int cur = 0;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle bundle = this.getArguments();
    if (bundle != null) {
        mChosenTime = bundle.getInt("TIME", 1);
    }

    switch (mChosenTime) {
        case timePicker1:
            cur = timePicker1;
            return new TimePickerDialog(getActivity(),AlertDialog.THEME_HOLO_DARK, this, hour, minute, DateFormat.is24HourFormat(getActivity()));
    }
    return null;
}

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    if (cur == timePicker1) {
        TextView alarmTimePicker01 = (TextView) getActivity().findViewById(R.id.alarmTimePicker01);
        alarmTimePicker01.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
        aHour1 = valueOf(hourOfDay);
        aMin1 = valueOf(minute);
}

(* I think my code is some kind of... 'strange'. Sorry about that :( )


Solution

  • You can use something like this

    Calendar cal= Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 9);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        PendingIntent pi = PendingIntent.getService(context, 0,
            new Intent(context, MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
       am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                                AlarmManager.INTERVAL_DAY, pi);
    

    Hope this works for you.