您好我正在實現一個自定義asynctaskloader加載數據在後臺。問題在於,當用戶在最小化應用程序(或從照片中選取照片)後重新開始活動時,所有與活動關聯的異步加載器和與活動中的片段關聯的異步加載器都會重新開始。Asynctaskloader重新啓動時重新加載活動
如何防止加載程序在重新啓動活動時重新啓動加載過程?
我baseAsynctaskLoader類:
import android.content.Context;
進口android.support.v4.content.AsyncTaskLoader; import android.util.Log;
公共抽象類BaseAsyncTaskLoader延伸AsyncTaskLoader {
private static final String TAG = "BaseAsyncTaskLoader";
protected Context context;
protected Object mData;
public BaseAsyncTaskLoader(Context context) {
super(context);
Log.d(TAG, "BaseLoader");
this.context = context.getApplicationContext();
}
@Override
public abstract Object loadInBackground();
@Override
public void deliverResult(Object data){
Log.d(TAG, "deliverResult");
if (isReset()) {
return;
}
mData = data;
if (isStarted()) {
super.deliverResult(data);
}
}
@Override
protected void onStartLoading(){
Log.d(TAG, "onStartLoading");
if (mData != null) {
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
}
@Override
protected void onStopLoading(){
Log.d(TAG, "onStopLoading");
cancelLoad();
}
@Override
protected void onReset(){
Log.d(TAG, "onReset");
super.onReset();
onStopLoading();
if(mData !=null){
mData=null;
}
}
@Override
public void onCanceled(Object data){
Log.d(TAG, "onCanceled");
super.onCanceled(data);
}
}
Loader類樣品:
public class AddDetailService extends BaseAsyncTaskLoader{
Activity activity;
Bundle bundle;
String outputstringrespone="";
public AddCarService(Activity activity, Bundle bundle){
super(activity);
this.activity = activity;
this.bundle = bundle;
}
@Override
public Object loadInBackground(){
try{
int userId = bundle.getInt(USER_ID);
int modelId = bundle.getInt(MODEL_ID);
outputstringrespone = addDetails(userId, modelId);
}catch(Exception e){
Log.d(TAG, e.toString());
}
return null;
}
@Override
public void deliverResult(Object data){
super.deliverResult(data);
Log.d(TAG,"output--"+outputstringrespone);
if(outputstringrespone.equalsIgnoreCase("Success")){
Toast.makeText(activity, "Details Added Successfully", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(activity, "Details not added",Toast.LENGTH_SHORT).show();
}
}
}
LoaderCallback活性:
getLoaderManager()。initLoader(LoaderId.ADD_DETAIL,bundle,addDetailsCallbacks);
LoaderManager.LoaderCallbacks addDetailsCallbacks = new LoaderManager.LoaderCallbacks(){
@Override
public Loader onCreateLoader(int id, Bundle args){
return new AddDetailService(getActivity(), args);
}
@Override
public void onLoadFinished(Loader loader, Object data){
getLoaderManager().destroyLoader(LoaderId.ADD_DETAIL);
}
@Override
public void onLoaderReset(Loader loader){
}
};