Asynctask Android

Asked

Viewed 184 times

3

I have a "Runnable" method that executes in 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?

Follow 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();
}
  • 2

    The class Asynctask also creates a new Thread. Here I give a small explanation between choosing one class or another.

1 answer

2

Leonardo, It’s almost like shooting a pigeon with a 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);
    }

}

Utilizing

// -- 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’d make the class ExecutaTask.java a class static to be used as a "utility" for any actions.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.