我有一段代码,我想在其中处理被点击文件的下载:
else if (url.startsWith("http://rapahh.com/songs2/Music%20Promotion/Download/")) {
}
return false;
虽然我不知道如何在Android中处理下载,但任何人都有一段代码可以用来在后台将文件下载到文件夹中。。下载文件夹很好。谢谢
您正在为哪个版本的android构建?
从API 9级开始,下载管理器可以为您处理此问题。如果可能的话,你应该使用DownloadManager,因为它会自动处理网络中断并为你恢复下载。
如果你的目标是低于API级别,你必须自己下载代码。您将有一个来自web源的inputStream和一个指向本地文件的outputStream,您将循环使用inputStream写入块,直到没有剩余的块为止。类似这样的东西:
try {
URL url = new URL(URL); //URL of the video
//Set our file to the correct path and name.
File file = new File(PATH + fileName);
//keep the start time so we can display how long it took to the Log.
long startTime = System.currentTimeMillis();
Log.d(myTag, "download begining");
//Log.d(myTag, "download url:" + url);
Log.d(myTag, "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = ucon.getContentLength();
Log.i(myTag, "Opened Connection");
/************************************************
* Define InputStreams to read from the URLConnection.
************************************************/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Log.i(myTag, "Got InputStream and BufferedInputStream");
/************************************************
* Define OutputStreams to write to our file.
************************************************/
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
Log.i(myTag, "Got FileOutputStream and BufferedOutputStream");
/************************************************
* Start reading the and writing our file.
************************************************/
byte data[] = new byte[1024];
long total = 0;
int count;
//loop and read the current chunk
while ((count = bis.read(data)) != -1) {
//Post our progress update back to the UI thread
postProgress((int)(total*100/lenghtOfFile));
//write this chunk
total += count;
bos.write(data, 0, count);
}
//Have to call flush or the video file can get corrupted and won't play correctly.
bos.flush();
bos.close();
Log.d(myTag, "download ready in "
+ ((System.currentTimeMillis() - startTime))
+ " milisec");
} catch (IOException e) {
Log.d(myTag, "Error: " + e);
}
您需要实现postProgress(int progress)
方法来执行任何适合您的应用程序的操作,以通知用户下载完成的百分比
编辑:
您可以对日志进行注释以使其正常工作。不过,我在调试时会让它们保持打开状态,以使过程更容易。日志语句,如Log.i(String tag, String text)
类似于System.out.println(String txt)
。不同之处在于,这些语句被打印到日志文件中(您可以在eclipse中的DDMS透视图中看到(。它们还有一个名为"tag"的附加参数,您可以将它传递给任何您喜欢的字符串,这个字符串将显示在日志文件中的文本旁边。您还可以在DDMS透视图中过滤这些标记上的日志输出。通常的做法是将您的标记声明为静态字符串,这样您就可以在所有日志语句中使用对它的引用,并保证始终具有相同的标记。所以,如果你在你的类中添加这样的东西,它应该会修复你的错误:
final static String myTag = "NameOfYourActivity";