Asynctask with one or more methods

Asked

Viewed 107 times

1

I would like to know the advantages and disadvantages of using an extended class of AsyncTask, which contains only one or more methods.

Example:

  • I create a AsyncTask for each background processing that I will utilise.

or

  • I create a AsyncTask for all processing, and within it I create several methods, and I call them with a parameter when instantiating the class ?

It is something to be considered, or only in terms of organization, need, preference, or even good practices ?

1 answer

1


Not only in this case but whatever the situation may/should consider other approaches.

However it should take into account not the organisation, necessity, preference, or even good practice but rather what is most appropriate for the situation in question.

You should start by considering using an Asynctask for each processing.
If, during development, you find that there are processes with similar characteristics you may consider writing a single class to process them.

Not in the way you describe your second example, which, if I have understood correctly, will require the implementation of some logic to be able to handle the different processing. This will not only complicate the class but complicate its use.

That’s why I mentioned "processing with similar characteristics". For example, if you have a set of processes that do not return anything and require a Progressbar to be displayed, you can write an extended Asynctask class where you implement all methods except the doInBackground().

When you have such a processing all you need to do is implement this method:

new GenericAsyncTask() {
    @Override
    protected Void doInBackground(Void... voids) {

        //inserir aqui o processamento a executar
        return null;
    }
}.execute();

This is just one example, others will depend on the type of processing.

  • Exactly in this context to have several "equal" needs, and so create an Asynctask with various methods, and by parameter, you pass which should be called, and in doInBackground does the if to call the relative method. For example a calculator with time-consuming calculations, which can calculate in various ways but will always only have 1 number as input and 1 output result. About Generictask, it would be instantiated within any class ?

  • Not "like" the solution of having several if however, as I say in the reply, if you think it is appropriate to your case use. Yes can be instantiated in any class, as long as the instance is created in UI thread.

Browser other questions tagged

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