您可以制作一个单独的抽象包私有类,扩展AsyncTask
和实现doInBackground()
方法:
abstract class MyAsyncTask extends AsyncTask<Void, Void, String> {
@Override
final protected String doInBackground(Void... progress) {
// do stuff, common to both activities in here
}
}
并且在您的活动中只是继承自MyAsyncTask
(顺便说一下,新类可能应该是私有的),实现onPostExecute()
和onPreExecute()
方法:
public class Activity_1 extends BaseActivity {
...
new Async1().execute();
...
private class Async1 extends MyAsyncTask {
@Override
protected void onPreExecute(){
// Activity 1 GUI stuff
}
@Override
protected void onPostExecute(String result) {
// Activity 1 GUI stuff
}
}
}
如果onPreExecute
并且还onPostExecute
包含一些常见操作,您可以应用以下模式:
abstract class MyAsyncTask extends AsyncTask<Void, Void, String> {
public interface MyAsyncTaskListener {
void onPreExecuteConcluded();
void onPostExecuteConcluded(String result);
}
private MyAsyncTaskListener mListener;
final public void setListener(MyAsyncTaskListener listener) {
mListener = listener;
}
@Override
final protected String doInBackground(Void... progress) {
// do stuff, common to both activities in here
}
@Override
final protected void onPreExecute() {
// common stuff
...
if (mListener != null)
mListener.onPreExecuteConcluded();
}
@Override
final protected void onPostExecute(String result) {
// common stuff
...
if (mListener != null)
mListener.onPostExecuteConcluded(result);
}
}
并在您的活动中使用它,如下所示:
public class Activity_1 extends BaseActivity {
...
MyAsyncTask aTask = new MyAsyncTask();
aTask.setListener(new MyAsyncTask.MyAsyncTaskListener() {
@Override
void onPreExecuteConcluded() {
// gui stuff
}
@Override
void onPostExecuteConcluded(String result) {
// gui stuff
}
});
aTask.execute();
...
}
你也可以拥有你的Activity
工具MyAsyncTaskListener
:
public class Activity_1 extends BaseActivity implements MyAsyncTask.MyAsyncTaskListener {
@Override
void onPreExecuteConcluded() {
// gui stuff
}
@Override
void onPostExecuteConcluded(String result) {
// gui stuff
}
...
MyAsyncTask aTask = new MyAsyncTask();
aTask.setListener(this);
aTask.execute();
...
}
我从头开始编写代码,因此它可能包含错误,但它应该说明这个想法。