Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Alternatives to AsyncTask?

Tags:

for my app I made a framework for all network calls to an external API. I put everything in "Services" like: UserService, MessageService etc. So now when I want to call a network method I can't do this in the UI-Thread of my Activity so I made an AsyncTask and everything was just fine =)

But now I want something like giving the method to execute to the AsyncTask so I don't need to write an AsyncTask for every method of my network-framework. So instead of having something like this:

public class NetworkTask extends AsyncTask<UserService, Void, Void> {      @Override     protected Void doInBackground(UserService... params) {         UserService userService = params[0];         userService.getUser();         return null;     } } 

I want something more "abstract" so the AsyncTask doesn't need to know the "getUser" method? But I can't find any idea of how to do this... Maybe the AsyncTask is not good for this anyway?

like image 360
cherry-wave Avatar asked May 23 '15 18:05

cherry-wave


People also ask

What replaces AsyncTask android?

AsyncTask is used to perform time talking operations in android, but it's marked as deprecated from android 11. There are many alternatives are available for replacing an AsyncTask, one of the replacements is ExecutorService.

Can I still use AsyncTask?

AsyncTask Alternatives Since AsyncTask is deprecated now, it leaves a bit of a void that must be filled by some other concurrency approach. So, let's discuss AsyncTask alternatives. If you just start your Android journey and use Java, I recommend the combo of bare Thread class and UI Handler.

How do I convert AsyncTask to Coroutine?

Replacing AsyncTask with Coroutines Replacing this with a coroutine is easy. Just use the async() method. Kotlin's async() runs on whichever Thread it was launched on, but does it asynchronously. This means you can update Views and such without having to worry about using the right Thread.


2 Answers

There are plenty AsyncTask alternatives :

https://android-arsenal.com/tag/9

and plus Needle - Multithreading library for Android

http://zsoltsafrany.github.io/needle/

like image 90
WebComer Avatar answered Sep 18 '22 14:09

WebComer


Maybe you can use a third party library like Retrofit If you work with images I strongly suggest picasso

like image 34
SebastianGreen Avatar answered Sep 17 '22 14:09

SebastianGreen