您的位置:首页 > 移动开发 > Android开发

android利用系统自带的DownloadManager下载文件

2015-03-08 09:40 435 查看
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri uri = Uri.parse("http://203.192.6.150//data/cdn_transfer/23/0F/231f8797d999fc6b67a264bdaefc638ce711e90f.mp4");
Request request = new Request(uri);
// 设置允许使用的网络类型,这里是移动网络和wifi都可以
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
SystemClock.sleep(2000);
// 禁止发出通知,既后台下载,如果要使用这一句必须声明一个权限:android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
//request.setShowRunningNotification(false);
// 不显示下载界面
request.setVisibleInDownloadsUi(true);
/*
* 调用setDestinationInExternalFilesDir,设置下载后文件存放的位置,如果sdcard不可用,那么设置这个将报错,因此最好不设置如果sdcard可用,下载后的文件
* 在/mnt/sdcard/Android/data/packageName/files目录下面,如果sdcard不可用,
* 设置了下面这个将报错,不设置,下载后的文件在/cache这个 目录下面
*/
request.setDestinationInExternalFilesDir(MainActivity.this, null, "tar.mp4");
long id = downloadManager.enqueue(request);

public class CompleteReceiver extends BroadcastReceiver {

private DownloadManager downloadManager;

@Override
public void onReceive(Context context, Intent intent) {

String action = intent.getAction();
if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Toast.makeText(context, "下载完成了....", Toast.LENGTH_LONG).show();

long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); // TODO
// 判断这个id与之前的id是否相等,如果相等说明是之前的那个要下载的文件
Query query = new Query();
query.setFilterById(id);
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor cursor = downloadManager.query(query);

int columnCount = cursor.getColumnCount();
String path = null; // TODO 这里把所有的列都打印一下,有什么需求,就怎么处理,文件的本地路径就是path
while (cursor.moveToNext()) {
for (int j = 0; j < columnCount; j++) {
String columnName = cursor.getColumnName(j);
String string = cursor.getString(j);
if (columnName.equals("local_uri")) {
path = string;
}
if (string != null) {
Log.i("MainActivity",columnName + ": " + string);
} else {
Log.i("MainActivity",columnName + ": null");
}
}
}
cursor.close();
// 如果sdcard不可用时下载下来的文件,那么这里将是一个内容提供者的路径,这里打印出来,有什么需求就怎么样处理
// if(path.startsWith("content:")) {
cursor = context.getContentResolver().query(Uri.parse(path), null,
null, null, null);
if(cursor != null){
columnCount = cursor.getColumnCount();
while (cursor.moveToNext()) {
for (int j = 0; j < columnCount; j++) {
String columnName = cursor.getColumnName(j);
String string = cursor.getString(j);
if (string != null) {
System.out.println(columnName + ": " + string);
} else {
System.out.println(columnName + ": null");
}
}
}
cursor.close();
}
} else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
Toast.makeText(context, "通知", Toast.LENGTH_LONG).show();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息