【发布时间】:2014-06-30 06:09:05
【问题描述】:
我有一个 Android 应用程序,它使用一个单独的类与服务器通信。这工作正常,但是当我按下应用程序上的按钮(将消息发送到服务器)时,按钮变为灰色并且一切都挂起,直到收到响应。我宁愿让应用显示 ProgressDialog,以便用户可以看到肯定发生的事情(而不是仅仅认为它被冻结了)。
我曾尝试使用 AsyncTask 执行此操作,但由于某种原因它不起作用。
这是我用来与服务器通信的类:
public class ServerConnection extends AsyncTask<String, Void, String> {
private Context context;
private ProgressDialog dialog;
public ServerConnection(Context ctx){
context = ctx;
dialog = new ProgressDialog(context);
dialog.setTitle("Waiting...");
dialog.setMessage("...on the world to change.");
}
@Override
protected void onPreExecute() {
dialog.show();
}
@Override
protected void onPostExecute(String unused) {
dialog.dismiss();
}
protected String doInBackground(String... msg) {
String response = null;
try{
/**
*
* Connects to server, sends message to server, waits for and receives a reponse from server
*
**/
} catch(Exception e) {
e.printStackTrace();
}
return response;
}
}
这就是我使用它的方式(请注意,这些行将从 Activity 中的某些方法中调用):
ServerConnection conn = new ServerConnection(this);
String response = null;
try {
response = conn.execute("ThisIsAMessageToTheServer").get();
} catch (Exception e){e.printStackTrace();}
当我单击一个按钮时,会执行一小段代码,几秒钟后,会收到来自服务器的响应。因此,就与服务器的通信和正确的响应而言,代码绝对可以正常工作。唯一的问题是 ProgressDialog 永远不会显示。
我浏览了谷歌,遇到的每个示例似乎都与此完全一样,所以我不确定是什么导致了问题。
【问题讨论】:
-
execute() 后删除 .get()
-
@RiteshGune 这绝对使对话工作!有什么方法可以在不使用 get() 的情况下将“响应”返回给 Activity?
-
在 doInBackground 中获得的响应将被传递给你的 asynctask 的 onPostExecute()。在后期执行中,您可以使用接口使用回调方法将结果发送回您的活动。
标签: java android android-asynctask progressdialog