我有一个MainActivity和一个AsyncTask类。当我将其称为myTask时,MainActivity效果很好。
但是如何从MainActivity调用myTask的onPostExecute结果。
这是我的第一个问题,如果我错了,我深表歉意。
myTask类
public class myTask extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog;
DownloadCallback mDownloadCallback;
Exception mException;
Context mContext;
JSONArray PHPfromArray= null;
String status="", message="";
private OkHttpClient client = new OkHttpClient();
public myTask(Context context, DownloadCallback downloadCallback) {
mContext = context;
mDownloadCallback = downloadCallback;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setMessage("Downloading.. ");
mProgressDialog.show();
}
@Override
protected String doInBackground(String... p) {
String jsonData = null;
return null;
}
@Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
if ( result== null )
{
mDownloadCallback.onFailure(mException);
} else {
mDownloadCallback.onSuccess(durum);
}
}
public interface DownloadCallback
{
void onSuccess(String downloadedString);
void onFailure(Exception exception);
}
}
此代码不起作用,如何从MainActivity调用?
new myTask(this, new myTask() {
@Override
public void onSuccess(String downloadedString) {
}
@Override
public void onFailure(Exception exception) {
}
});
答案 0 :(得分:0)
您可以这样修改myTask
:
....
public myTask(Context context){
mContext = context;
}//firstly modify constructor
public void setCallback(DownloadCallback downloadCallback){
mDownloadCallback = downloadCallback;
}//add a function
...
然后您可以在活动中实现android,如下所示:
public class MainActivity extends AppCompatActivity implements myTask.DownloadCallback {
...
final myTask myTask = new myTask(MainActivity.this);
myTask.setCallback(MainActivity.this);
myTask.execute();
@Override
public void onSuccess(String downloadedString) {
}
@Override
public void onFailure(Exception exception) {
}
}