线程中的Android全局变量

时间:2012-07-25 19:24:08

标签: java android multithreading variables global

我有问题。这是我的代码:

public String getXmlFromUrl(String url) {
    String xml = null;

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                xml = EntityUtils.toString(httpEntity);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).run();
    // return XML
    return xml;
}

那么,如何在我的线程中使用url以及如何返回xml?

感谢您的帮助

4 个答案:

答案 0 :(得分:3)

Android提供AsyncTask,完全符合您的目标。

示例:

private class XMLTask extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        // Do stuff
        // For example showing a Dialog to give some feedback to the user.
    }

    @Override
    protected String doInBackground(.. parameters..) {
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } 
        return xml;
    }

    @Override
    protected void onPostExecute(String xml) {
        // If you have created a Dialog, here is the place to dismiss it.
        // The `xml` that you returned will be passed to this method
        xml.Dowhateveryouwant

        }
    }
}

答案 1 :(得分:0)

2件事:

  • 此方法是同步调用,因此最好使用AsyncTask。
  • 使用Thread.start()启动一个帖子。

答案 2 :(得分:0)

url最终使用它。

如果您在完成其他线程之前不介意阻止,请将xml变为AtomicReference,并在致电Thread.start()之后(注意您应该'不'呼叫{{1} - 这不会产生另一个线程),使用一些同步工具(例如Thread.run())等待线程完成后再返回CountdownLatch

但是如果你不介意阻塞,为什么不在没有单独线程的情况下执行代码呢?如果无法阻止,则无法返回xml值 - 您必须更改设计,可能执行xml并异步提供结果。

答案 3 :(得分:0)

您可以将您的网址标记为final,并在您的Runnable中使用它,如下所示:

public String getXmlFromUrl(final String url) {
    // ...
}

您可能希望定义一个无状态回调方法或类,您可以调用它来处理XML响应。你可以这样称呼它:

xml = EntityUtils.toString(httpEntity);
handleXmlResponse(xml);

如果您愿意,可以将方法handleXmlResponse定义为包含getXmlFromUrl方法的类的私有方法。

您可能想要考虑的一件事是使用Executors类获取newSingleThreadExecutor并将Runnable传递给它,而不是每次要获取某些XML时都创建新的Thread:

https://developer.android.com/reference/java/util/concurrent/Executors.html#newSingleThreadExecutor%28%29

以下是一个例子:

ExecutorService mThreadPool = Executors.newSingleThreadExecutor();
public String getXmlFromUrl(String url) {
    String xml = null;

        // Note the change here. Everything else remains the same.
        mThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                xml = EntityUtils.toString(httpEntity);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    // return XML
    return xml;
}