AsyncTask Android

3

I have a "Runnable" method that executes on a new Thread a certain method to update my list.

Every time I call this "Runnable", I'm creating a new Thread, which for me is not very positive ...

How can I do the same thing using an AsyncTask?

Here's my method:

public void atualizaLista(){
    Thread t = new Thread("Thread1") {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    // Atualiza lista
                    atualiza();
                }
            });
        }
    };
    t.start();
}
    
asked by anonymous 29.06.2015 / 21:11

1 answer

2

Leonardo , it's almost like killing a pigeon with bazooka but try:

ExecutaTask.java

package com.seudominio.seuapp;

class ExecutaTask extends AsyncTask<Void, Void, Void>
{
    /**
     * Ação como TIPO
     */
    public interface AcaoExecutaTask { void executa(); }
    private AcaoExecutaTask acao;

    public ExecutaTask(AcaoExecutaTask acao)
    {
        this.acao = acao;
    }

    /**
     * Antes de executar.
     */
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    /**
     * A ação.
     */
    @Override
    protected Void doInBackground(Void... params)
    {

        // Ação desejada aqui
        if(acao != null)
            acao.executa();

        return null;
    }

    /**
     * Depois de executar.
     */
    @Override
    protected void onPostExecute(Void aVoid)
    {
        super.onPostExecute(aVoid);
    }

}

Usage

// -- ação de executar (ahhh como no C# isto é bem mais fácil que no Java)
ExecutaTask.AcaoExecutaTask acao = new ExecutaTask.AcaoExecutaTask()
{
    @Override
    public void executa()
    {
        // Atualiza lista
        atualiza();
    }
};

new ExecutaTask(acao).execute();

I would make the class ExecutaTask.java a class static to be used as a "utility" for any actions.

Tip : You can easily implement callback using the same ideology as public interface AcaoExecutaTask { void executa(); }

    
29.06.2015 / 21:35