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 を空として出力する print 関数を配置しない場合です。postreq.execute(dict)

私は a で待機を強制しましたWHILEが、WHILEそれはメインスレッドをブロックします。

メソッドが実行されるまで待ってから、値をRESULT非同期的に変数に代入するにはどうすればよいですか?

たとえば、Windows Phone の C# では、次のようにしました。

 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

AsyncTask を見てください。while ループで別のスレッドからの結果を繰り返しチェックすることはお勧めできません。

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

于 2013-06-05T14:43:29.203 に答える