我在java文件中有一个AsyncTask
类,然后我有一堆其他活动,我将调用这个AsyncTask
类。现在doInBackground
方法总是做同样的事情,但是在每个活动中我想用返回的数据做不同的事情。所以它看起来像这样
public class MakePOSTAsync extends AsyncTask<Object, Integer, String> {
@Override
protected String doInBackground(Object... obj) {
//thisIsAlwaysTheSame
}
@Override
protected void onPostExecute(String string){
//I want to make a method call in the activity where I am calling
//this AsyncTask??
}
那么如何在不同的活动中调用一个方法,显然它会有相同的名称,但我不能ActivityName.method();
因为我将在不同的活动中调用它?
由于
答案 0 :(得分:3)
将对您的活动的引用传递给MakePOSTAsync。最好的方法是将它作为WeakReference存储在AsyncTask中 - 这将防止引用泄漏。实际上你应该创建一个接口,并传递对这个接口的引用。您的每个活动都将实现此界面。
示例代码:
// Common interface
interface DataLoadCallback {
void startLoading();
void loaded(String someData);
}
// Some activity or fragment
public class MyActivity extends Activity implements DataLoadCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MakePOSTAsync(this).execute();
// dont forget to manage lifetime of AsyncTask, like
// cancel it in case of activity gets destroyed. Or switch to Loader.
}
}
// In MakePOSTAsync.java
public class MakePOSTAsync extends AsyncTask<Object, Integer, String> {
private WeakReference<DataLoadCallback> callbackRef;
public MakePOSTAsync(DataLoadCallback callback) {
callbackRef = new WeakReference<DataLoadCallback>(callback);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
DataLoadCallback ref = callbackRef.get();
if (ref != null) {
ref.startLoading(); // show progress in activity?
}
}
@Override
protected String doInBackground(Object... obj) {
//thisIsAlwaysTheSame
}
@Override
protected void onPostExecute(String string) {
DataLoadCallback ref = callbackRef.get();
if (ref != null) {
ref.loaded(string);
}
}
}
答案 1 :(得分:1)
请勿在{{1}}中实施:
MakePOSTAsync
但在活动中:
public abstract class MakePOSTAsync extends AsyncTask<Object, Integer, String> {
@Override
protected String doInBackground(Object... obj) {
//thisIsAlwaysTheSame
}
protected abstract void onPostExecute(String string);
}
答案 2 :(得分:1)
创建一个回调接口:
public class MakePOSTAsync extends AsyncTask<Object, Integer, String> {
private WeakReference<Callback> mCallback;
interface Callback {
void doSomething();
}
public MakePOSTAsync(Callback callback){
mCallback = new WeakReference<Callback>(callback);
}
@Override
protected String doInBackground(Object... params) {
return null;
}
@Override
protected void onPostExecute(String string){
if(mCallback.get() != null){
mCallback.get().doSomething();
}
}
}
让你的活动实现它:
public class MainActivity extends AppCompatActivity implements
MakePOSTAsync.Callback{
...
@Override
public void doSomething() {
}
//Then you can start your task, passing in the callback implementation in the constructor
private void startTask() {
new MakePOSTAsync(this).execute();
}
}