4

I'm making a simple Alarm Clock app, to study BroadcastReceivers , the problem is getHours() and getMinutes() are only available for API 23.

  • Is there any alternative way of achieving this?
  • If so? Will it possible solution be applicable to higher API like 24?

Here's my sample code: AlarmActivity.java

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm);

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    setWidgets();

    Intent intent = new Intent(this.context, AlarmReceivers.class);

}

public void setWidgets(){
    timePicker = (TimePicker) findViewById(R.id.timePicker);
    //Calendar calendar = Calendar.getInstance();

    buttonSetAlarm = (Button) findViewById(R.id.buttonSetAlarm);
    buttonSetAlarm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int getHour = timePicker.getHour();
            int getMinute = timePicker.getMinute();

            calendar.set(Calendar.HOUR_OF_DAY,timePicker.getHour());
            calendar.set(java.util.Calendar.MINUTE, timePicker.getMinute());

            if (getHour > 12){
                int twelve = getHour - 12;
            }

            if (getMinute < 10){

            }

            setText("On");

        }
    });

I'm stuck with the getHour() and getMinute().

RoCkDevstack
  • 3,517
  • 7
  • 34
  • 56

2 Answers2

14

As getHour() and getMinute() are for API 23 and above, if your application targets lower APIs you need to add support for them.

You can do this by adding the following:

if(Build.VERSION.SDK_INT < 23){
    int getHour = timePicker.getCurrentHour();
    int getMinute = timePicker.getCurrentMinute();

    calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
    calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
} else{
    int getHour = timePicker.getHour();
    int getMinute = timePicker.getMinute();

    calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
    calendar.set(Calendar.MINUTE, timePicker.getMinute());
}

Both getCurrentHour() and getCurrentMinute() are deprecated but still work on lower APIs.

GoateedDev
  • 139
  • 1
  • 6
2

You can use the get() Methode from the Calendar class.

calendar.get(Calendar.HOUR);
calendar.get(Calendar.MINUTE);
Lasse Sb
  • 81
  • 9