下载时如何停止/取消文件?我正在使用 urlconnection 和 inputstream。代码有效,但我无法取消下载。我的下载代码:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),8192);
File myDir = getDir(Environment.DIRECTORY_MUSIC,
Context.MODE_PRIVATE);
Intent i = getIntent();
String name = i.getStringExtra("name");
File mypath = new File(myDir, name + ".mp3");
mypath.createNewFile();
mypath.mkdirs();
OutputStream output = new FileOutputStream(mypath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}