Use loader for asynchronous processing in Android
2024.3.9
2017.10.3
Asynchronous processing using AsyncTask is essential for usability, but AsyncTask also has its drawbacks. To work around it, it is better to use a loader.
Disadvantages of AsyncTask
When an activity is called, a new task is created for asynchronous processing, but when the phone changes direction and the activity is updated, for example, another task is created. This is quite inefficient because it waits for the previous process to finish before discarding it and creating a new task.
Therefore, instead of discarding and re-generating tasks, use a loader that can process tasks regardless of the start or end of an activity.
Implementation
Import packages
import android.content.Loader;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
Interface
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<D> { ... }
Methods
When you implement an interface, you must either write all the methods provided in the interface or make MainActivity.class
itself an abstract
class.
@Override
public Loader<D> onCreateLoader(int id, Bundle args) {
return new ExampleLoader();
}
@Override
public void onLoadFinished(Loader<D> loader, D data) {
// some processes
}
@Override
public void onLoaderReset(Loader<D> loader) {
// some processes
}
The process is written in the loadInBackground()
method of a class that extends AsyncTaskLoader
.
import android.content.AsyncTaskLoader;
import android.content.Context;
public class ExampleLoader extends AsyncTaskLoader<D> {
public ExampleLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public D loadInBackground() {
//何らかの処理
return 結果;
}
}
Intialize the loader
For an activity, initialize the loader in onCreate()
. It can be applied to one activity or one fragment at a time.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(0, null, this);
}
The first argument of initLoader()
is an ID, and loaders are managed by IDs. When the same ID is initialized, if it does not exist, a new loader is created; if it exists, the previous loader is reused, so that when the activity is updated, the result of previous processing can be used.