图像下载服务多余的资源使用

时间:2016-04-28 07:01:11

标签: android performance android-service

我正在开发一个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();

1 个答案:

答案 0 :(得分: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());
    }