1

出于某种原因,每次用户在使用 3g 数据时单击下载按钮,屏幕就会完全变黑,并且应用程序会请求强制关闭。

    private final String PATH = Environment.getExternalStorageDirectory() + "/folder";


    public void DownloadFromUrl(String fileName, String saveTo) {  
            try {
                    URL url = new URL("http://example.com/" + fileName + ".png");
                    File file = new File(fileName + ".png");

                    long startTime = System.currentTimeMillis();

                    URLConnection urlconnection = url.openConnection();




                    InputStream iS = urlconnection.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(iS);


                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                            baf.append((byte) current);
                    }


                    FileOutputStream fos = new FileOutputStream(PATH + saveTo);
                    fos.write(baf.toByteArray());
                    fos.close();
                    Toast t= Toast.makeText(getApplicationContext(), "Downloaded '" + saveTo + "' to '" + PATH + "'.", Toast.LENGTH_SHORT);
                    t.show();
            } catch (IOException e) {
                    Log.d("ImageManager", "Error: " + e);
            }

    }
4

2 回答 2

2

因为您正在使用长时间运行的操作阻塞 UI 线程。

相反,请尝试在后台线程、HandlerServiceIntentServiceAsyncTask或其他线程中发出请求,这样 UI 线程就不会卡住。

于 2012-11-30T03:52:59.143 回答
2

这里的优秀教程:http ://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

此外,从 google android api中查看ASYNC作为@Robert 建议的选项:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
于 2012-11-30T04:13:45.800 回答