对AsyncTask
进行子类化以使其可以在多个活动中重用的正确方法是什么?
我有多个活动都使用相同的AsyncTask
来获取一些JSON数据。唯一的区别是每个Activity都有自己的ProgressBar
来显示activty和它自己的 processResult 来处理返回的JSON数据。我想继承AsyncTask
,以便我可以传递对ProgressBar
的引用,以便设置相应的Activity的ProgressBar可见性,并将返回的数据传递给该Activity& #39; s processResults()。
以下是典型活动的摘要:
public class MyActivity extends AppCompatActivity {
private ProgressBar mProgessBar;
private List<Object> myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
mProgessBar = (ProgressBar) findViewById(R.id.myProgessBar);
myList = new ArrayList<Object>();
getData();
}
private void getData() {
//All async tasks take string variables
new BGGetData().execute("Something", "Something", "Dark side", null);
}
private void processResults(JSONObject data) {
//Different types of data for different activities.
//process JSON results to fill myList or do something other action with the data
}
///////
//BACKGROUND TASK IS REPEATED IN MULTIPLE ACTIVITIES
///////
public class BGGetData extends AsyncTask<String, Void, JSONObject> {
@Override
protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected JSONObject doInBackground(String... params) {
// do something to get a jsonobject
return json;
}
@Override
protected void onPostExecute(JSONObject data) {
mProgressBar.setVisibility(View.GONE);
processResults(data);
}
}
}