public class FileDownLoad {
private long id;
private DownloadManager manager;
private DownloadManager.Request request;
private RequestCompleteReceiver completeReceiver;
private String type;
private String suffix;
public FileDownLoad(Context context,String url,String type){
completeReceiver=new RequestCompleteReceiver();
context.registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
this.type=type;
manager=(DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
request=new DownloadManager.Request(Uri.parse(url));
//设置可用的网络类型
request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
//设置状态栏中显示Notification API Level 11
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//不显示下载界面
request.setVisibleInDownloadsUi(true);
//设备存在SD卡则设置下载后文件存放的位置,否则不设置
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File file=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(!file.exists()){
file.mkdirs();
}
Log.e("TAG", file.getAbsolutePath());
if("apk".equals(type))
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "ybs.apk");
else if("xls".equals(type)){
suffix=url.substring(url.lastIndexOf("/")+1);
Log.e("xls下载地址","xls下载地址"+Environment.DIRECTORY_DOWNLOADS+"/"+suffix);
Log.e("xls下载地址","报表名字="+suffix);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, suffix);
}
}
//设置文件类型
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
request.setMimeType(mimeString);
}
public void enqueue(Context context,String title,String description){
if(id!=0){
manager.remove(id);
id=0;
}
//标题
request.setTitle(title);
//描述信息
request.setDescription(description);
id=manager.enqueue(request);
}
private File paths;
class RequestCompleteReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
if("apk".equals(type)){
//下载完成
long downloadCompleteId=intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
if(downloadCompleteId==id){
context.unregisterReceiver(completeReceiver);
completeReceiver=null;
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);//设置过滤状态:成功
Cursor c = manager.query(query);// 查询以前下载过的‘成功文件’
String uriStr="";
if (c.moveToFirst()) {// 移动到最新下载的文件
uriStr = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.e("下载路径uri", uriStr);
}
Toast.makeText(context, "新版本下载完成", Toast.LENGTH_SHORT).show();
Intent intent_=new Intent(Intent.ACTION_VIEW);
intent_.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
//有SD卡设置过下载路径
//file:///storage/emulated/0/Download/ybs-28.apk
if(!TextUtils.isEmpty(uriStr)){
//context.startActivity(intent_);
intent_.setDataAndType(Uri.parse(uriStr), "application/vnd.android.package-archive");
}
}else{
//未设置过下载路径
File file=new File(getFilePathFromUri(context, Uri.parse(uriStr)));
if(file!=null){
//context.startActivity(intent_);
intent_.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
}
}
}else if("xls".equals(type)){
paths = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("tag", "报表路径="+paths);
String fileName = suffix;
Log.i("tag", "报表名字="+fileName);
context.unregisterReceiver(completeReceiver);
completeReceiver=null;
//File file=new File(("file://"+path),fileName);
/* Intent data=new Intent(Intent.ACTION_SEND);
data.putExtra(Intent.EXTRA_EMAIL,ary);
data.putExtra(Intent.EXTRA_SUBJECT, "导出数据excel报表的数据"); //这是标题
data.putExtra(Intent.EXTRA_TEXT,"报表在您的附件里,请查收!");
data.setType("application/vnd.ms-excel");
// data.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); //添加附件,附件为file对象
data.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///storage/emulated/0/Download/210440353315737.xls"));//添加附件,附件为file对象
context.startActivity(data);*/
}
}
}
}
public String getFilePath(){
if(paths!=null&&completeReceiver==null){
String s="file://"+paths+"/"+suffix;
return s;
}
return "";
}
/**为了兼容低版本的API会出现以下问题
*
* 1.当有SD卡设置了下载路径以后,下载完成广播返回的字符串类型的Uri路径类似file:///storage/emulated/0/Download/ybs-28.apk
* 可直接被 intent_.setDataAndType识别,正常安装
* 2.当因为SD卡没有不设置下载路径的时候,系统默认下载路径:/data/data/com.android.providers.downloads/cache/
* 下载完成广播返回的字符串类型的Uri路径类似 content://downloads/my_download/15
* 但是这种Uri发现不能直接被 intent_.setDataAndType识别,会报包解析失败问题;
* 可以使用如下方法来得到文件的实际路径再转uri来打开
* @param c
* @param uri
* @return
*/
public String getFilePathFromUri(Context c, Uri uri) {
String filePath = null;
if ("content".equals(uri.getScheme())) {
String[] filePathColumn = { MediaColumns.DATA };
ContentResolver contentResolver = c.getContentResolver();
Cursor cursor = contentResolver.query(uri, filePathColumn, null,
null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
} else if ("file".equals(uri.getScheme())) {
filePath = new File(uri.getPath()).getAbsolutePath();
}
return filePath;
}
}