【发布时间】:2018-03-27 14:07:04
【问题描述】:
在使用AsyncTask 运行后台任务后,我尝试将变量更新为后台任务的结果。变量更新,但显然不准时。我用来显示服务器响应的吐司首先显示一个空吐司,然后第二次显示一个非空吐司(这会弄乱我的代码中的所有内容,因为按时收到的响应是它所需要的)。
在发布代码之前,我需要指出,如果我在 UI 线程上运行代码的替代版本(同时在 UI 线程上强制连接),我没有任何问题。该变量将使用该变量进行更新。
String databaseCheckResult = "";
private class AsyncCheckIfExists extends AsyncTask<String, Integer, String> {
String result = null;
@Override
protected void onPreExecute(){
}
@Override
protected String doInBackground(String... formValues) {
try {
URL url = new URL(formValues[1]);
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches (false);
String urlParameters = "date=" + formValues[0];
byte[] postData = urlParameters.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(postData);
os.flush();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// success, get result from server
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
conn.disconnect();
result = response.toString();
return result;
} else {
// error
//TODO: let the user know that something is wrong with the network
}
} catch (java.io.IOException e) {
//TODO: prevent app from crashing
}
} catch (java.net.MalformedURLException e){
//TODO: prevent app from crashing
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress){
}
@Override
protected void onPostExecute(String message){
databaseCheckResult = message;
}
}
我称之为:
AsyncCheckIfExists check = new AsyncCheckIfExists();
check.execute(date, "http://www.webaddress.com/script.php");
【问题讨论】:
-
我没有看到任何
Toast。对于您的问题,一旦doInbackground()完成,它将返回到onPostExcceute(),其中包含在 UI 线程上调用的数据。您可以在任何地方更新实例变量。阅读AsyncTask 调用周期。如果问题仍然存在,请澄清您的问题。 -
Toast 是由我活动中的另一种方法启动的。
标签: android android-asynctask background-task background-thread