下载超过3g时,为什么应用程序崩溃,而不是通过WiFi?

时间:2012-11-30 03:49:14

标签: android crash download

出于某种原因,每次用户在使用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);
            }

    }

2 个答案:

答案 0 :(得分:2)

因为您使用长时间运行的操作阻止了UI线程。

相反,请尝试在后台线程HandlerServiceIntentServiceAsyncTask或其他内容中发出请求,因此UI线程无法获取卡住。

答案 1 :(得分:2)

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

另外,请查看ASYNC from google android api @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");
     }
 }