android - 从互联网获取数据时应用卡住

标签 android httpclient freeze

我遇到了一个问题,我确信它很容易解决,但我仍在开始应用程序开发,所以我认为你可以帮助我。 我有一个应用程序,里面有一个货币转换器,当我按下按钮进行转换时,它在从互联网获取数据时卡住,然后在几秒钟后恢复正常。这是代码:

   public void capturaConversao(String m1, String m2) throws ClientProtocolException, IOException {
        BufferedReader resp = null;
        endereco = "http://download.finance.yahoo.com/d/quotes.csv?s=" + m1
                + m2 + "=X&f=sl1d1t1ba&e=.csv";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet method = new HttpGet(endereco);
            HttpResponse statusCode = client.execute(method);
            resp = new BufferedReader(new InputStreamReader(statusCode
                    .getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            while ((line = resp.readLine()) != null) {
                sb.append(line);
            }
            resp.close();
            String result = sb.toString();
            String[] values = result.split(",");
            conversion = values[1];
            nextstep++;

        } finally {
            if (resp != null) {
                try {
                    resp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getBaseContext(), "Não foi possível se conectar à internet.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

最佳答案

AsyncTask是几乎所有 UI 线程问题的解决方案。 :) 这是一个简短的 tutorial .

关于android - 从互联网获取数据时应用卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6433876/

相关文章:

android - 当用户打开抽屉时调用函数(onClick 按钮或幻灯片)

javascript - 我正在开发 XDK 应用程序。使用此代码进行的任何更正

android - 在 Android 上训练 Tesseract

angular - 在 Angular 项目中将 Http 迁移到 HttpClient

angular - 使用 ngx-leaflet、HTTPClient 和 Angular2+ 将 GeoJSON 数据获取到 Leaflet map

c# - HttpClient 在上传前读取整个文件。 UWP

linux - 无法在 Armbian Stretch 上预编译 Microsoft.CodeAnalysis.CSharp

linux - 如何卡住Linux中的文件夹?

ASP.NET 挂起 - 通用字典并发问题导致 GC 死锁

android - 在不重置的情况下终止android服务