Use Activity.runOnUiThread () or Handler.post (Runnable) to update the main Thread?

2

Very good, I have a question related to when I have to use (or why) Activity.runOnUiThread () instead of, or vice versa Handler.post (Runnable) strong> to update for example a TextView or ProgressBar , or alternatively, I should use Asyntask .

I have been looking for information in the following links, but I still do not have a clear answer. What is the best option depending on each case?

Android: What's the difference between Activity.runOnUiThread and View.post?

runOnUiThread vs. Handler.post (runnable action)?

Difference between Handler.post (Runnable r) and Activity.runOnUiThread (Runnable r)

    
asked by dddenis 08.06.2016 в 13:08
source

1 answer

3

The difference between Activity.runOnUiThread() and Handler.post(Runnable r) is that the runOnUiThread only executes a specific action from a thread that you are running on a view (a component , either TextView or another) of the main thread l, that is, a component of your app.

The Handler.post (Runnable r), basically serves the same purpose, but there is a small difference and that with Handler.post () you can access the components or variables of other thread and not just the thread main with runOnUiThread .

If you only want to modify a component of the main thread, I recommend that you use runOnUiThread() since this way you will not have problems.

An example of using runOnUiThread() is:

runOnUiThread(new Runnable() {
   @Override
   public void run() {
       // Código a ejecutar
   }
}

An example of using Handler.post(Runnable r) is:

handler.post(new Runnable() {
    @Override
    public void run() {
        // Código a ejecutar
    }
 });

Another thing is to use AsyncTask , which has specific methods to create actions in the main thread, but can not access its components, for example, a AsycnTask can use its methods to create a dialog with a bar of process and act on it, but you can not access a TextView the main thread.

I give an example:

private class HiloEnSegundoPlano extends AsyncTask <(los parametros que recibe o que le envias), (el tipo de datos que maneja durante la ejecución), (el tipo de datos en devuelve)> {

        public HiloEnSegundoPlano(){
            // Es el constructor
        }

        @Override
        protected void onPreExecute() {
            // Este método puede actuar sobre el hilo principal y por ejmplo,
            // aquí es donde abririas un dialogo con una barra de proceso.
        }

        @Override
        protected (el tipo de datos en devuelve) doInBackground((los parametros que recibe o que le envias)... variable (ejemplo: "args")) {
            // Aquí iria el código que quieres ejecutar en segundo plano.

            publishProgress(el tipo de datos que maneja durante la ejecución); 
            // Es opcional y con el puedes pasar un valor y llamar a onProgressUpdate()

            cancel(true); 
            //Es opcional y con el puedes cancelar la tarea y llamará al método onCancelled() en vez de pasar onPostExecute(). Puedes comprobar si se ha cancelado con isCancelled().

            return (el valor del tipo de datos en devuelve);
        }

        @Override
        protected void onProgressUpdate((tipo de dato)... variable (ejemplo: "args")) {
            // Aquí podrias tener alguna acción en el cuadro de dialogo abierto, por ejmplo,
            // repetir un codigo 50 veces para dibujar un proceso de carga.
        }

        @Override
        protected void onPostExecute((tipo de datos en devuelve) variable) {
            // Aqui cerrarias el cuadro de dialogo, en caso, de que todo se haya ejecutado 
            // correctamente.
        }

        @Override
        protected void onCancelled ((tipo de datos en devuelve) variable) {
            // Aqui cerrarias el cuadro de dialogo, en caso, de que se haya producido algun
            // error en la carga y desde el método "doInBackground" hayas ejecutado "cancel(true);"
            // Podrías mostrar también un mensaje de error.
        }

I hope I have helped you with your doubt. If you have any other questions or do not understand something that I explain, please leave a comment and I will clarify it.

Good luck!

    
answered by 08.06.2016 / 14:04
source