当我完成HttpURLConnection时,我做的是哪个
inputStream.close();
urlConnection.disconnect();
或
urlConnection.disconnect();
inputStream.close();
答案 0 :(得分:1)
关闭输入流就足够了。如果断开连接,则禁用HTTP连接池。
答案 1 :(得分:-3)
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public static float FILE_SIZE = 0;
public static int SUM = 0;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
// String urlToDownload = intent.getStringExtra("url");
int fileLength = 0;
int size = 0;
String urlarray[] = intent.getStringArrayExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
URLConnection connection = null;
int result = 0;
try {
URL url = null;
for (String url_ : urlarray) {
url = new URL(url_);
connection = url.openConnection();
connection.connect();
fileLength = connection.getContentLength();
size = size + fileLength;
// File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/ImageApp/");
dir.mkdirs();
File file1 = new File(dir, System.currentTimeMillis() + ".png");
OutputStream output = new FileOutputStream(file1);
if (file1.createNewFile()) {
file1.createNewFile();
}
InputStream input = new BufferedInputStream(connection.getInputStream());
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
result = (int) (total * 100 / fileLength);
Bundle resultData = new Bundle();
resultData.putInt("progress", result);
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
Bundle resultData = new Bundle();
receiver.send(UPDATE_PROGRESS, resultData);
SUM++;
output.flush();
output.close();
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
FILE_SIZE = size / 1024;
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}