2016-04-28 6 views
1

ImageDownloadServiceで作業しています。問題は、それが私のアプリからイメージを連続的にダウンロードして、私の電話をハングすることです。私は、ダウンロードサービスが多すぎるリソースを使用していると考えています。特定のRAM使用量を超えた場合、サービスが遅くなるようにしたい。 リソース使用量に制限を設ける方法を教えてもらえますか?イメージダウンロードサービスリソースの超過使用

URL url = new URL(imageUrl)); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setDoInput(true); 
connection.connect(); 
InputStream is = connection.getInputStream(); 
String imageName = "IMAGE_" + System.currentTimeMillis() + ".png"; 
File image = new File(directoryPath, imageName); 
FileOutputStream out = new FileOutputStream(image); 
byte[] buffer = new byte[1024]; 
int bytesRead; 
while ((bytesRead = is.read(buffer)) > 0) { 
    out.write(buffer, 0, bytesRead); 
} 
is.close(); 
out.flush(); 
out.close(); 
connection.disconnect(); 
+0

イメージを読み込むためにグライドのようなライブラリを使用してみてください。 – YakuZa

+0

3番目の部分ライブラリを使用したくない場合は、[DownloadManager](http://developer.android.com/intl/ru/reference/android/app/DownloadManager.html)を使用して、 – Alexander

答えて

0

私はこれを使用してイメージをダウンロードしています。

try { 
     URL url = new URL(url); 
     URLConnection conection = url.openConnection(); 
     conection.connect(); 
     // getting file length 
     int lenghtOfFile = conection.getContentLength(); 

     // input stream to read file - with 8k buffer 
     InputStream input = new BufferedInputStream(url.openStream(), 8192); 

     // Output stream to write file 
     OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg"); 

     byte data[] = new byte[1024]; 

     long total = 0; 

     while ((count = input.read(data)) != -1) { 
      total += count; 

      // writing data to file 
      output.write(data, 0, count); 
     } 

     // flushing output 
     output.flush(); 

     // closing streams 
     output.close(); 
     input.close(); 

    } catch (Exception e) { 
     Log.e("Error: ", e.getMessage()); 
    } 
関連する問題