Because the java calendar does not work for hours and minutes

0

My problem is simple: because this method does not work for me when it's time is more than 30 minutes. I do not know exactly if it is for 30 but for 1 hour and 30 minutes it does not work. It just does not enter run () method of the Tempor class that inherits from TimerTask. But if I set it for seconds if it works.

public void TactivarBroucast(int a,int b) { //a y b el tiempo en horas (a) y el tiempo en minutos (b)
       long t=b*3600000+a*60000; //1s = 1000ms 1m=60000 
      Log.d("metodo",String.valueOf(System.currentTimeMillis()+t));
       Date date = new Date(System.currentTimeMillis()+t);
       Calendar c = Calendar.getInstance();
       c.setTime(date);
      // c.set(Calendar.HOUR,b);
      //   c.set(Calendar.MILLISECOND,(int) t);
       date = c.getTime();
       Timer time = new Timer();
       time.schedule(new Temporisador(), date);
   }

The lines that are commented on is because I already tried and it did not work. I also understand that the AlarmManager can be used. How would the latter be? It should be noted that I am making an android application. How can I do to schedule a task on android to run after X time (hours and minutes)? Thanks in advance.

    
asked by Andry_UCI 25.03.2018 в 14:04
source

2 answers

2

Try to be more explicit in the names of your variables

public static void main(String[] args) {
    int hora = 1;
    int mins = 30;

    final long t = (hora * 60 + mins) * 60 * 1000;

    Date date = new Date(System.currentTimeMillis() + t);
    Calendar c = Calendar.getInstance();
    c.setTime(date);

    Timer time = new Timer();
    time.schedule(new TimerTask() {
        public void run() {
            System.out.println("Running!");
        }
    }, date);
}

This code worked for me, you are probably confusing the semantics of the variables to and b

Notes:

  • the method should not be called broadCast?
  • methods in java, by convention should start with a lowercase letter, ex tActivaBroadcast ()
  • beware of Temporisator, it has an error, it should be Timer (this time if it is capitalized because it is a class)
  • answered by 25.03.2018 в 18:49
    0

    You must use add to add hours / minutes to a certain date:

    Calendar c = Calendar.getInstance();  //obtienes la fecha de este momento (now)
    c.add(Calendar.HOUR_OF_DAY,a);      //agregas las horas(a) a la hora actual
    c.add(Calendar.MINUTE,b);          //agregas los minutos(b) a la hora/minutos actual
    Timer time = new Timer();
    time.schedule(new Temporisador(), c.getTime());     //obtienes la fecha actualizada
    

    a and b must be int .

        
    answered by 25.03.2018 в 20:53