Buscar..


Observaciones

Un controlador se puede usar fácilmente para ejecutar código después de un período de tiempo retrasado. También es útil para ejecutar el código repetidamente después de un período de tiempo específico llamando nuevamente al método Handler.postDelayed () desde el método run () de Runnable.

Uso de un controlador para ejecutar código después de un período de tiempo retrasado

Ejecutando código después de 1.5 segundos:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        //The code you want to run after the time is up
    }
}, 1500); //the time you want to delay in milliseconds

Ejecutando código repetidamente cada 1 segundo:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        handler.postDelayed(this, 1000);
    }
}, 1000); //the time you want to delay in milliseconds

HandlerThreads y comunicación entre hilos.

Como los Handler se utilizan para enviar Message y Runnable a la cola de mensajes de un subproceso, es fácil implementar una comunicación basada en eventos entre varios subprocesos. Cada hilo que tiene un Looper puede recibir y procesar mensajes. Un HandlerThread es un subproceso que implementa tal Looper , por ejemplo, el subproceso principal (UI Thread) implementa las características de un HandlerThread .

Creación de un controlador para el hilo actual

Handler handler = new Handler();

Creación de un controlador para el subproceso principal (subproceso de la interfaz de usuario)

Handler handler = new Handler(Looper.getMainLooper());

Enviar un Runnable de otro hilo al hilo principal

new Thread(new Runnable() {
    public void run() {
        // this is executed on another Thread

        // create a Handler associated with the main Thread
        Handler handler = new Handler(Looper.getMainLooper());

        // post a Runnable to the main Thread
        handler.post(new Runnable() {
            public void run() {
                // this is executed on the main Thread
            }
        });
    }
}).start();

Creando un Handler para otro HandlerThread y enviándole eventos

// create another Thread
HandlerThread otherThread = new HandlerThread("name");

// create a Handler associated with the other Thread
Handler handler = new Handler(otherThread.getLooper());

// post an event to the other Thread
handler.post(new Runnable() {
    public void run() {
        // this is executed on the other Thread
    }
});

Detener el manejador de la ejecución

Para detener la ejecución del controlador, elimine la devolución de llamada adjunta utilizando el ejecutable ejecutable dentro de él:

Runnable my_runnable = new Runnable() {
    @Override
    public void run() {
        // your code here
    }
};

public Handler handler = new Handler(); // use 'new Handler(Looper.getMainLooper());' if you want this handler to control something in the UI
// to start the handler
public void start() {
    handler.postDelayed(my_runnable, 10000);
}

// to stop the handler
public void stop() {
    handler.removeCallbacks(my_runnable);
}

// to reset the handler
public void restart() {
    handler.removeCallbacks(my_runnable);
    handler.postDelayed(my_runnable, 10000);
}

Use el controlador para crear un temporizador (similar a javax.swing.Timer)

Esto puede ser útil si estás escribiendo un juego o algo que necesita ejecutar un fragmento de código cada pocos segundos.

import android.os.Handler;

public class Timer {
    private Handler handler;
    private boolean paused;

    private int interval;

    private Runnable task = new Runnable () {
        @Override
        public void run() {
            if (!paused) {
                runnable.run ();
                Timer.this.handler.postDelayed (this, interval);
            }
        }
    };

    private Runnable runnable;

    public int getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public void startTimer () {
        paused = false;
        handler.postDelayed (task, interval);
    }

    public void stopTimer () {
        paused = true;
    }

    public Timer (Runnable runnable, int interval, boolean started) {
        handler = new Handler ();
        this.runnable = runnable;
        this.interval = interval;
        if (started)
            startTimer ();
    }
}

Ejemplo de uso:

Timer timer = new Timer(new Runnable() {
    public void run() {
        System.out.println("Hello");
    }
}, 1000, true)

Este código imprimirá "Hola" cada segundo.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow