【发布时间】:2014-04-20 17:05:29
【问题描述】:
我正在从我的 android 应用程序调用服务器。我已经使用 AsyncTask 线程完成了这项工作。 现在我已经在 onPreExecute() 方法中启动了 Progress Dialog,如下:
protected void onPreExecute(){
dialog = new ProgressDialog(appcontext);
dialog.setMessage("Sending Position...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
现在,在 doInBackground() 方法中,我一直在执行发送数据的任务。在收到响应后,我将使用 onPostExecute() 方法使用 dialog.dismiss() 来停止 ProgressDialog。
我的 doInBackGround() 代码
protected String doInBackground(Position... position){
InputStream inputStream = null;
String temp=null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2:8084/WebApplication5/getData");
String json = "";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("time",position[0].getTime());
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content", "application/json");
org.apache.http.HttpResponse httpResponse = httpclient.execute(httpPost);
**// CODE ACTUALLY BLOCKS HERE UNTIL I GET A RESPONSE.(WHAT I THINKS). THOUGH WORKS 99%**
inputStream = httpResponse.getEntity().getContent();
if(inputStream!=null)
temp="sent";
}
catch (JSONException e){
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return temp;
}
一切都很好,但有时我没有得到响应(让它成为任何服务器错误),在这种情况下,对话框无法关闭并且无限期地运行。我想将 doInBackGround() 方法的持续时间限制为几秒钟。这样即使在没有响应的情况下,它也会移动到 onPostExecute() 并且我的无限对话应该停止。
其次,如果我收到回复,我想将其保存到我的 SharedPreferences,所以我的问题是最好的方法是什么,即
1) 我应该在 onPause() 方法中进行。
2) 或者,在 onStop() 方法中,
3) 或在 onPostExecut()e 方法中
否则没有意义,我可以在任何地方做。
我的最后一个问题是共享首选项中存储的数据的生命周期是多少。
【问题讨论】:
-
也发布 onPostExecute 代码。 --- 你的 doBackground 将完成你应该添加一些报告失败的东西。或者添加更多关于 doBackground 的信息
-
在 postExecute 我只是在使用 dialog.dismiss() 并开始其他活动。
-
如果出现问题,您的 doBackground 将永远运行吗?添加doBackground代码,不正常。
-
我已经编辑了这个问题。请再看一遍..
标签: java android android-asynctask sharedpreferences progressdialog