我构建/复制了一个下载功能,通过URL获取图像和视频,并将其下载到Android设备。
下载小图片时没问题。但是当试图获取超过2MB
的文件(通过WLAN!)时,它需要几乎年龄! 25MB视频约需5分钟,等等。
任何想法可能出错?
这是我的代码:
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
答案 0 :(得分:1)
使用DownloadManager下载文件
private long enqueue;
private DownloadManager dm;
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
Log.e("Download completed","HERE DOWNLOAD COMPLETED");
try
{
}
catch (Exception e) {
// TODO: handle exception
}
}
}
}
}};
要开始此下载,请使用:
dm = (DownloadManager)activityContext.getSystemService(activityContext.DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse("URL")).setDestinationInExternalPublicDir("DIRECTORY","FILENAME");
enqueue = dm.enqueue(request);