Ответ 1
Проверьте концепцию AsyncTaskLoader
. Эта функция поддерживается сообществом Android, представленным на уровне API 11 наряду с функциями Honeycomb.
AsyncTaskLoader
решил множество ограничений и обходных решений AsyncTask.java
Официальный: https://developer.android.com/reference/android/content/AsyncTaskLoader.html
Хороший пример: https://medium.com/google-developers/making-loading-data-on-android-lifecycle-aware-897e12760832
public class JsonAsyncTaskLoader extends AsyncTaskLoader<List<String>> {
// You probably have something more complicated
// than just a String. Roll with me
private List<String> mData;
public JsonAsyncTaskLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
if (mData != null) {
// Use cached data
deliverResult(mData);
} else {
// We have no data, so kick off loading it
forceLoad();
}
}
@Override
public List<String> loadInBackground() {
// This is on a background thread
// Good to know: the Context returned by getContext()
// is the application context
File jsonFile = new File(
getContext().getFilesDir(), "downloaded.json");
List<String> data = new ArrayList<>();
// Parse the JSON using the library of your choice
// Check isLoadInBackgroundCanceled() to cancel out early
return data;
}
@Override
public void deliverResult(List<String> data) {
// We’ll save the data for later retrieval
mData = data;
// We can do any pre-processing we want here
// Just remember this is on the UI thread so nothing lengthy!
super.deliverResult(data);
}
}