我所有的异步调用都在它们自己的类中,所以我不想将全局变量设置为异步。为此,我想返回对象,例如来 self 的 asunc postProcess 方法的字符串。
这可以做到吗?
下面是我的类的一般结构,我想从 onPostExecute() 返回一个字符串。我看到其他地方提到了委托(delegate),但这看起来很困惑,确定有一种方法可以为类或方法提供返回类型吗?
class GetStuffAsyncly extends AsyncTask<String, String, String>
{
// my vars....
public myconstructor(String dialogMessage, Context con)
{
this.qDialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
}
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute()
{
super.onPreExecute();
do stuff like fire dialog
}
@Override
protected String doInBackground(String... args)
{
// do stuff in background...
return data;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String jsonString)
{
// dismiss the dialog after getting all data
dialog.dismiss();
}
}
最佳答案
像下面这样的东西
class GetStuffAsyncly extends AsyncTask<String, String, String> {
String dialogString;
ProgressDialog dialog;
Context context;
AsyncListener listener;
// my vars....
public GetStuffAsyncly(String dialogMessage, Context con, AsyncListener listener) {
this.dialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
this.listener = listener;
}
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
listener.onTaskStarted();
}
@Override
protected String doInBackground(String... args) {
// do stuff in background...
return data;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String jsonString) {
// dismiss the dialog after getting all data
dialog.dismiss();
listener.onTaskFinished(jsonString);
}
}
以及监听器类
public interface AsyncListener {
void onTaskStarted();
void onTaskFinished(String data);
}
你可以这样调用
new GetStuffAsyncly(message, this, new AsyncListener() {
@Override
public void onTaskStarted() {
//do your stuff
}
@Override
public void onTaskFinished(String data) {
//Do your stuff;
}
}).execute(parameter);
关于java - 如何从异步调用返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33918148/