0
 public void btnWeb_Click(View view){
     String url="http://localhost/test/index.php";

     List<NameValuePair> dict = new ArrayList<NameValuePair>();
     dict.add(new BasicNameValuePair("url",url));
     dict.add(new BasicNameValuePair("id", "3"));

     PostReq postreq= new PostReq();
     postreq.execute(dict);

     String result="";
     while(result==""){ result= postreq.content;}  
     System.out.println(result); }

PostReq是异步执行对服务器的 Post 请求的类。

问题是,如果我不放while,打印函数将变量 RESULT 打印为空,因为它没有等待线程postreq.execute(dict)完成操作。

我用 a 强制等待,WHILE但这WHILE会阻塞主线程。

如何等到方法执行完毕,然后将值RESULT异步分配给变量?

例如,在 C# for Windows Phone 中,我是这样做的:

 async void button_click() {
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("id", "3");
string url="http://localhost/test/index.php";
    PostReq pr= new PostReq(url,dict);
    String risposta = await pr.getRisposta(); }

使用 Java for Android 而不是我该怎么办?

4

1 回答 1

0

看看异步任务。在 while 循环中重复检查来自另一个线程的结果不是一个好主意。

http://developer.android.com/reference/android/os/AsyncTask.html

于 2013-06-05T14:43:29.203 回答