android LoaderManager与AsyncTaskLoader,java(1)
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.AsyncTaskLoader;
import androidx.loader.content.Loader;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static String TAG = "fly";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoaderManager loaderManager = LoaderManager.getInstance(this);
loaderManager.initLoader(2023, new Bundle(), new LoaderManager.LoaderCallbacks<String>() {
@NonNull
@Override
public MyLoader<String> onCreateLoader(int id, @Nullable Bundle args) {
Log.d(TAG, "onCreateLoader - id - " + id);
MyLoader loader = new MyLoader(getApplicationContext());
Log.d(TAG, "onCreateLoader - getId() - " + loader.getId());
return loader;
}
@Override
public void onLoadFinished(@NonNull Loader<String> loader, String data) {
Log.d(TAG, "onLoadFinished - " + loader.getId() + " - " + data);
}
@Override
public void onLoaderReset(@NonNull Loader<String> loader) {
}
});
//loaderManager.getLoader(2023).startLoading(); 不需要调用,自动执行
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "----------");
Log.d(TAG, "onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
private static class MyLoader<String> extends AsyncTaskLoader<String> {
public MyLoader(@NonNull Context context) {
super(context);
Log.d(TAG, "MyLoader - " + getId());
}
@Override
protected void onStartLoading() {
super.onStartLoading();
Log.d(TAG, "onStartLoading - " + getId());
this.forceLoad();//如果没有,则不会触发loadInBackground
}
//work thread
@Nullable
@Override
public String loadInBackground() {
String s = (String) ("fly@" + System.currentTimeMillis());
return s;
}
//UI main thread
@Override
public void deliverResult(@Nullable String data) {
super.deliverResult(data);
Log.d(TAG, "deliverResult - " + getId() + " " + data);
}
}
}
输出: