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
Loaders should be used instead of directly using Async tasks. There are specific Loader API's for specific operations like perform transations in sqlite database etc.
Remember that Android has a limit of threads and AsyncTasks.
You can use 2 libraries to do the same work of AsyncTasks:
1) Volley -> http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
2) LoopJ -> http://loopj.com/android-async-http/
UPDATE
I really recommend Retrofit 2. http://square.github.io/retrofit/
Good luck in your choice.
Regards,
Uilton.
You can use Volley library which does it work on the background thread and gives you control back to main thread when things are done.
RxJAVA is best option
Alternative to Asynctask for Web service call,file upload,file download is Android Fast Networking Lib
For other case you can use following method
Disposable d = Observable.fromCallable(new Callable<HashMap<String, String>>() {
@Override
public HashMap<String, String> call() throws Exception {
// will run in background thread (same as doinBackground)
return postParam;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<HashMap<String, String>>() {
@Override
public void accept(final HashMap<String, String> data) throws Exception {
// will run in UI thread. write down code for on PostExecute
}
});
// write down code for on preExecute
DisposableManager.add(d);
// dispose object
@Override
protected void onDestroy() {
super.onDestroy();
DisposableManager.dispose();
}
// Dispose manager class
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
public class DisposableManager {
private static CompositeDisposable compositeDisposable;
public static void add(Disposable disposable) {
getCompositeDisposable().add(disposable);
}
public static void dispose() {
getCompositeDisposable().dispose();
}
private static CompositeDisposable getCompositeDisposable() {
if (compositeDisposable == null || compositeDisposable.isDisposed()) {
compositeDisposable = new CompositeDisposable();
}
return compositeDisposable;
}
private DisposableManager() {}
}
There are plenty AsyncTask alternatives :
https://android-arsenal.com/tag/9
and plus Needle - Multithreading library for Android
http://zsoltsafrany.github.io/needle/
Maybe you can use a third party library like Retrofit If you work with images I strongly suggest picasso