博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android调用系统内部的下载程序下载文件(二)
阅读量:4103 次
发布时间:2019-05-25

本文共 7244 字,大约阅读时间需要 24 分钟。

本文地址:

android2.3及以后,系统把内部的下载程序开放出来了。让我们可以使用DownloadManager这个类了。使用方法如下:

[java]
  1.     DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
  2.          
  3.     Uri uri = Uri.parse("fileUrl"); 
  4.     Request request = new Request(uri); 
  5.  
  6.     //设置允许使用的网络类型,这里是移动网络和wifi都可以   
  7.     request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);   
  8.  
  9.     //禁止发出通知,既后台下载,如果要使用这一句必须声明一个权限:android.permission.DOWNLOAD_WITHOUT_NOTIFICATION   
  10.     //request.setShowRunningNotification(false);   
  11.  
  12.     //不显示下载界面   
  13.     request.setVisibleInDownloadsUi(false); 
  14.         /*设置下载后文件存放的位置,如果sdcard不可用,那么设置这个将报错,因此最好不设置如果sdcard可用,下载后的文件        在/mnt/sdcard/Android/data/packageName/files目录下面,如果sdcard不可用,设置了下面这个将报错,不设置,下载后的文件在/cache这个  目录下面*/ 
  15. //request.setDestinationInExternalFilesDir(this, null, "tar.apk"); 
  16. long id = downloadManager.enqueue(request); 
  17. //TODO 把id保存好,在接收者里面要用,最好保存在Preferences里面 
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);			Uri uri = Uri.parse("fileUrl");	Request request = new Request(uri);	//设置允许使用的网络类型,这里是移动网络和wifi都可以  	request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);  	//禁止发出通知,既后台下载,如果要使用这一句必须声明一个权限:android.permission.DOWNLOAD_WITHOUT_NOTIFICATION  	//request.setShowRunningNotification(false);  	//不显示下载界面  	request.setVisibleInDownloadsUi(false);        /*设置下载后文件存放的位置,如果sdcard不可用,那么设置这个将报错,因此最好不设置如果sdcard可用,下载后的文件        在/mnt/sdcard/Android/data/packageName/files目录下面,如果sdcard不可用,设置了下面这个将报错,不设置,下载后的文件在/cache这个  目录下面*///request.setDestinationInExternalFilesDir(this, null, "tar.apk");long id = downloadManager.enqueue(request);//TODO 把id保存好,在接收者里面要用,最好保存在Preferences里面

这里注意的是这时候程序就必须至少声明两个权限:

[html]
  1. <uses-permission android:name="android.permission.INTERNET" />   
  2.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

用这个方法有好处,用户可以控制下载的过程,即如果没有下载完,并且不想下载了,可以终止下载,并且可以注册一个广播接收者,如果文件一下载完,就可以接收到一个广播。然后可以得到下载后的文件的路径:

[java]
  1. package cn.dotcreate.testProcess; 
  2.  
  3. import android.app.DownloadManager; 
  4. import android.app.DownloadManager.Query; 
  5. import android.content.BroadcastReceiver; 
  6. import android.content.Context; 
  7. import android.content.Intent; 
  8. import android.database.Cursor; 
  9. import android.net.Uri; 
  10. import android.widget.Toast; 
  11.  
  12. public class CompleteReceiver extends BroadcastReceiver { 
  13.  
  14.     private DownloadManager downloadManager; 
  15.  
  16.     @Override 
  17.     public void onReceive(Context context, Intent intent) { 
  18.          
  19.         String action = intent.getAction(); 
  20.         if(action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { 
  21.             Toast.makeText(context, "下载完成了....", Toast.LENGTH_LONG).show(); 
  22.              
  23.             long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);                                                                                      //TODO 判断这个id与之前的id是否相等,如果相等说明是之前的那个要下载的文件 
  24.             Query query = new Query(); 
  25.             query.setFilterById(id); 
  26.             downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); 
  27.             Cursor cursor = downloadManager.query(query); 
  28.              
  29.             int columnCount = cursor.getColumnCount(); 
  30.             String path = null;                                                                                                                                       //TODO 这里把所有的列都打印一下,有什么需求,就怎么处理,文件的本地路径就是path 
  31.             while(cursor.moveToNext()) { 
  32.                 for (int j = 0; j < columnCount; j++) { 
  33.                     String columnName = cursor.getColumnName(j); 
  34.                     String string = cursor.getString(j); 
  35.                     if(columnName.equals("local_uri")) { 
  36.                         path = string; 
  37.                     } 
  38.                     if(string != null) { 
  39.                         System.out.println(columnName+": "+ string); 
  40.                     }else
  41.                         System.out.println(columnName+": null"); 
  42.                     } 
  43.                 } 
  44.             } 
  45.             cursor.close(); 
  46.         //如果sdcard不可用时下载下来的文件,那么这里将是一个内容提供者的路径,这里打印出来,有什么需求就怎么样处理                                                   if(path.startsWith("content:")) {
     
  47.                                cursor = context.getContentResolver().query(Uri.parse(path), null, null, null, null); 
  48.                                columnCount = cursor.getColumnCount(); 
  49.                                while(cursor.moveToNext()) { 
  50.                                     for (int j = 0; j < columnCount; j++) { 
  51.                                                 String columnName = cursor.getColumnName(j); 
  52.                                                 String string = cursor.getString(j); 
  53.                                                 if(string != null) { 
  54.                                                      System.out.println(columnName+": "+ string); 
  55.                         }else
  56.                             System.out.println(columnName+": null"); 
  57.                         } 
  58.                     } 
  59.                 } 
  60.                 cursor.close(); 
  61.             } 
  62.              
  63.         }else if(action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) { 
  64.             Toast.makeText(context, "点击<span style="font-family: 宋体;">通知</span><span style="text-indent: 21pt; font-family: 宋体; font-size: 10.5pt;">了....", Toast.LENGTH_LONG).show();</span> 
  65.         } 
  66.     } 
package cn.dotcreate.testProcess;import android.app.DownloadManager;import android.app.DownloadManager.Query;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.widget.Toast;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) {						System.out.println(columnName+": "+ string);					}else {						System.out.println(columnName+": null");					}				}			}			cursor.close();		//如果sdcard不可用时下载下来的文件,那么这里将是一个内容提供者的路径,这里打印出来,有什么需求就怎么样处理                                                   if(path.startsWith("content:")) {                               cursor = context.getContentResolver().query(Uri.parse(path), null, null, null, 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();		}	}}

在清单里面注册当前这个receiver:

[html]
  1. <receiver android:name=".CompleteReceiver"> 
  2.             <intent-filter> 
  3.                 <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/> 
  4.                 <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/> 
  5.             </intent-filter> 
  6.         </receiver> 
    需要说明的是在如果手机的sdcard可用,那么在上面那一步里面的path就是sdcard上面的路径,如果sdcard不可用,那么那个路径将是一个内容提供者的路径。

转载地址:http://ucbsi.baihongyu.com/

你可能感兴趣的文章
Java异常分类
查看>>
项目中的jackson与json-lib使用比较
查看>>
Jackson Tree Model Example
查看>>
j2ee-验证码
查看>>
日志框架logj的使用
查看>>
js-高德地图规划路线
查看>>
常用js收集
查看>>
mydata97的日期控件
查看>>
如何防止sql注入
查看>>
maven多工程构建与打包
查看>>
springmvc传值
查看>>
Java 集合学习一 HashSet
查看>>
在Eclipse中查看Android源码
查看>>
Android-Socket登录实例
查看>>
Android使用webservice客户端实例
查看>>
层在页面中的定位
查看>>
[转]C语言printf
查看>>
C 语言 学习---获取文本框内容及字符串拼接
查看>>
C 语言学习 --设置文本框内容及进制转换
查看>>
C 语言 学习---判断文本框取得的数是否是整数
查看>>