目前在我的应用程序中,我执行一个 JSONDownloader,然后告诉我的应用程序等待一段时间,然后再用检索到的数据更新字段。在更新字段之前,如何让应用程序等待 JSONDownloader 完成其任务?
JSONDowloader 类的编写(删节)如下,并作为异步活动运行。需要时调用此类并设置全局变量,这些变量在被调用后的设定时间后会更新。我希望在课程结束后立即更新这些字段。
public class JSONDownloader extends AsyncTask<Object, Object, Object>{
@Override
protected Object doInBackground(Object... params) {
if(JSONstate == false){
try {
final URL url = new URL("https://irrelevant");
final URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.connect();
final InputStream inputStream = urlConnection.getInputStream();
final StringBuilder sb = new StringBuilder();
while (inputStream.available() > 0) {
sb.append((char) inputStream.read());
}
System.out.println("up to setting string");
String result = sb.toString();
JSONObject jsonOrg = new JSONObject(result);
String ok = "ok";
Response = jsonOrg.getString("response");
System.out.println(Response);
if(Response.equals(ok)){
Settingsresponse = true;
orgName = jsonOrg.getString("orgName");
System.out.println("orgName" + orgName);
accessPointName = jsonOrg.getString("accessPointName");
System.out.println("accessPointName" + accessPointName);
lat = jsonOrg.getString("latitude");
System.out.println("lat" + lat);
longi = jsonOrg.getString("longitude");
System.out.println("longi" + longi);
floor = jsonOrg.getString("floor");
System.out.println("floor" + floor);
orgId = jsonOrg.getString("orgId");
System.out.println("orgId" + orgId);
}
else{
System.out.println("Data sent was erroneous");
Settingsresponse = false;
}
} catch (Exception e) {
System.err.print(e);
}
}
return null;
}
protected void onPostExecute(Void result){
}
}
JSONDownloader 在它需要的任何方法中被调用,然后在它被调用之后立即被调用;目前在更新字段之前使用设定的时间,如下所示:
public void waitthencall()
{
long t0,t1;
t0=System.currentTimeMillis();
do{
t1=System.currentTimeMillis();
}
while (t1-t0<2000);
setfields();
}