我在AsyncTask doInBackground中有回调。我想在回调完成后更新UI。我的问题是我无法返回我的回调响应,所以我不知道如何做到这一点。基本上,我想将myString从我的回调响应返回到onPostExecute。
$url = "https://hidden-for-privacy-and-security-reasons";
$optional_headers = array("authorization: something valid is here","cache-control: no-cache", "content-type: application/json");
$params['http']['header'] = $optional_headers;
$context = stream_context_create($params);
$fpointer = fopen($url, 'r', false, $context);
if($fpointer !== false)
{
$resphdrs = stream_get_meta_data($fpointer);
if ($resphdrs["wrapper_data"][0] == "HTTP/1.1 201 Created")
{
error_log("SUCCESSFULLY received = " .$resphdrs["wrapper_data"][0], 0);
}
else
{
header($resphdrs["wrapper_data"][0]);
error_log("Some ERROR occurred= " .$resphdrs["wrapper_data"][0], 0);
}
}
else
{
header("HTTP/1.1 500 Internal Server Error");
error_log("500 error received", 0);
// echo $get_error_header[0];
}
答案 0 :(得分:1)
1- override
是一种您AsyncTask<Param, Progress, Result>
无法创建的方法。
2-将extends class更改为此//AsyncTask<Param, Progress, Result>
private class PotatoAsyncTask extends AsyncTask<Object, Void, String> {
private static String passedString;
PotatoAsyncTask() {
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// In the UI thread
// before calling doInBackground()
}
@Override
protected String doInBackground(Object... params) {
// In another thread than the UI thread
// do what you want here
Util.syncMessages(token, new Util.OnSyncMessages() {
@Override
public void onSyncMessages(boolean success, String myString) {
if (success) {
passedString = myString;
return; // this is not the return of doInBackground
}
}
});
return returnString;// return what you want in here
}
@Override
protected void onPostExecute(String returnString) {
super.onPostExecute(returnString);
// In UI thread
// after doInBackground is completely done
}
@Override
protected void onCancelled(String returnString) {
super.onCancelled(returnString);
// in case the doInBackground was cancelled at one point but there is still a result
}
@Override
protected void onCancelled() {
super.onCancelled();
//
}
}
,请参阅下面的示例
{{1}}
答案 1 :(得分:0)
似乎很难在内部类中返回值,希望这会有所帮助:
private class MyAsyncTask extends AsyncTask<Object, String, Void> {
MyAsyncTask() {
}
@Override
protected void doInBackground(Object... params) {
Util.syncMessages(token, new Util.OnSyncMessages() {
@Override
public void onSyncMessages(boolean success, String myString) {
if (success) {
//return myString; // can't return here
publishProgress(myString);
}
}
});
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
String str = values[0];
//do something with str in main Thread.
}
}