如何将AsyncTask切换到Loader最简单的方法?

时间:2017-07-24 03:18:14

标签: java android android-asynctask

如何从AsyncTask切换到Loader?我是否需要为loader创建一个新的java类?

我目前的代码:

}
private class ProcessJSON extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(MainActivity.this, R.string.loading, Toast.LENGTH_SHORT).show();
    }

    protected String doInBackground(String... strings) {
        String stream = null;
        String urlString = strings[0];

        GoogleAPI hh = new GoogleAPI();
        stream = hh.GetGoogleAPI(urlString);
        return stream;
    }

但是想将AsyncTask更改为Loader。怎么样? TQ

1 个答案:

答案 0 :(得分:0)

public class ProcessJSON extends AsyncTaskLoader<String> {
public ProcessJSON (Context context) {
    super(context);
}
@Override 
public String loadInBackground() {
    return "ProcessJSON";
  }
}

在您的活动中实现LoaderManager回调。

YourActivity

public class YourActivity extends Activity implements LoaderManager.LoaderCallbacks<String>{

 @Override
 public void onCreate(Bundle bundle){
 getSupportLoaderManager().initLoader(1, null, this).forceLoad();
 }

@Override 
public Loader<String> onCreateLoader(int id, Bundle args) {
  return new ProcessJSON(YourActivity.this);
}
@Override 
public void onLoadFinished(Loader<String> loader, List<Employee> data) {
 //do something on finished
}
@Override 
public void onLoaderReset(Loader<String> loader) {
//do something
}


}