How to use Timer and TimerTask tool

1

I want the program to check every second if the if condition is met, but I get some errors, I do not know what I'm doing wrong, this is the code:

package alarmexample.example.com.alarmexample;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends Activity {


public  String getHora(String strFormato) {

    Calendar objCalendar = Calendar.getInstance();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(strFormato);

    String strHora = simpleDateFormat.format(objCalendar.getTime());
    return strHora;
}

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

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            startAlert();}

public void startAlert() {

    String hora_sistema = getHora("HH:mm:"); //Obtenida con el método
    String horaTuya = "03:13:";

    int timeInSec = 5;

    if (horaTuya.equals(hora_sistema)) {

        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent);
        Toast.makeText(this, "La alarma sonará en " + timeInSec + " segundos", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "no hay nada ", Toast.LENGTH_SHORT).show();}
                     }
           },0,1000);//Cada segundo.
    }
}
    
asked by Alexander 04.04.2018 в 08:47
source

2 answers

1

Timer and TimerTask are not "tools", they are java classes that help you to schedule a single or repeated execution with a timer.

The startAlert(); method should be called within Handler , you should not call the declaration of the entire method within onCreate only startAlert(); :

public class MainActivity extends Activity {


    public  String getHora(String strFormato) {

        Calendar objCalendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(strFormato);

        String strHora = simpleDateFormat.format(objCalendar.getTime());
        return strHora;

    }

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

        final Handler handler = new Handler();
        final Runnable r = new Runnable() {
            public void run() {

                startAlert();  //*** Aquí!!!

                handler.postDelayed(this, 1000);
            }
        };

        handler.postDelayed(r, 1000);




    }   

   public void startAlert() {


        String hora_sistema = getHora("HH:mm"); //hora sistema
        String mihora = "23:57"; //hora establecida

        int timeInSec = 5;

        if ( mihora.equals(hora_sistema )){


            Toast.makeText(this, " hola,despierta ",Toast.LENGTH_SHORT).show();


        }else {Toast.makeText(this, "aún no es la hora ",Toast.LENGTH_SHORT).show();}
    }
}
    
answered by 04.04.2018 / 16:44
source
1

It would not hurt for you to indicate what mistakes you are talking about. Still and so I have seen the following:

1: You can not update the UI from inside the thread separate from the main one. Try this:

    timer.schedule(new TimerTask() {
        private Handler updateUI = new Handler(){
            @Override
            public void dispatchMessage(Message msg) {
                super.dispatchMessage(msg);
                startAlert();
            }
        };

        @Override
        public void run()
        {
            updateUI.sendEmptyMessage(0);
        }
    },0,1000);//Cada segundo.

2: Create the MyBroadcastReceiver class that extends from BroadcastReceiver.

    
answered by 04.04.2018 в 17:49