如何在继续之前等待结束一个线程

时间:2014-01-14 15:58:25

标签: java android multithreading http

我正在开发一个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", "knocka.a@gmail.com"));
                             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之前等待线程结束的解决方案。

谢谢!

2 个答案:

答案 0 :(得分:3)

不要使用普通的java Thread类,切换到AsyncTask,您将在doInBackground中执行OAuth网络作业,然后在完成后,您将在onPostExecute中执行所有UI更新。

答案 1 :(得分:1)

您不希望等待线程完成以返回令牌。这样做会锁定您的UI线程,如果Web请求需要几秒钟,您的用户将看到来自Android的消息,告诉他们您的应用没有响应,建议他们强制关闭它。

您要做的是更改代码以使用AsyncTask。请访问http://developer.android.com/reference/android/os/AsyncTask.html

了解详情