2014-01-14 65 views
0

我正在開發一個Android項目,我正在通過線程的問題,我正在做一個HTTP請求。如何等待最後一個線程再去之前

我試圖從API獲取令牌刷新令牌...。

下面是代碼:

public class OAuthHelper { 

    static TokenModel tokenObj; 
    final static CountDownLatch latch = new CountDownLatch(1); 

    public static TokenModel getTokens(final RequestModel request) throws InterruptedException{ 
     Thread thread = new Thread() 
     { 
      @Override 
      public void run() 
      { 
       try 
       { 
        try 
        { 
         HttpClient httpclient = new DefaultHttpClient(); 
         HttpPost httppost = new HttpPost("http://api.listopresto.com/oauth/token"); 
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
         if (request.getType() == "password"){ 
          Log.i("infos", "password"); 
          nameValuePairs.add(new BasicNameValuePair("grant_type", "password")); 
          nameValuePairs.add(new BasicNameValuePair("client_id", "antoine")); 
          nameValuePairs.add(new BasicNameValuePair("client_secret", "toto")); 
          nameValuePairs.add(new BasicNameValuePair("username", "[email protected]")); 
          nameValuePairs.add(new BasicNameValuePair("password", "toto"));        
         } 
         else{ 
          Log.i("infos", "refresh_token"); 
          nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token")); 
          nameValuePairs.add(new BasicNameValuePair("client_id", "antoine")); 
          nameValuePairs.add(new BasicNameValuePair("client_secret", "toto")); 
          nameValuePairs.add(new Bas icNameValuePair("refresh_token", request.getRefreshToken())); 
         } 
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); 
         HttpResponse response = httpclient.execute(httppost); 
         BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
         String s = reader.readLine(); 
         Gson gson = new Gson(); 
         tokenObj = gson.fromJson(s, new TypeToken<TokenModel>(){}.getType()); 
         latch.countDown(); 

        } catch (ClientProtocolException e) { 
         Log.i("infos", "first"); 
        } catch (IOException e) { 
         Log.i("infos", "second"); 
        } 
       } 
       catch (Exception e){ 
        Log.i("infos", "third"); 
       } 
      } 
    }; 
    thread.start(); 
    latch.await(); 
    return (tokenObj); 
    } 
} 

當我做一弗朗用戶名和密碼的請求是沒有問題的。我用令牌得到正確的對象...但是當我做第二個時,看起來我在線程結束之前返回tokenObj。我認爲我通過使用latch.await()解決了這個問題,但我仍然有問題。

我正在尋找一種解決方案,在返回tokenObj之前等待線程結束。

謝謝!

回答

3

不要使用普通的Java類Thread,切換到AsyncTask,你會做內部doInBackground您的OAuth網絡作業,然後它做了以後,你會做內部onPostExecute所有UI更新。

1

您不想等待您的線程完成以返回您的令牌。這樣做會鎖定您的UI線程,如果Web請求需要幾秒鐘時間,您的用戶會看到Android的消息,告訴他們您的應用程序沒有響應,並建議他們強制關閉它。

你想要做的是改變你的代碼以使用AsyncTask。瞭解更多,請登錄http://developer.android.com/reference/android/os/AsyncTask.html

相關問題