Android:如何使用下载pipe理器类?

我想从一个url下载一个二进制文件。 是否有可能使用我在这里find的DownloadManager类的Android下载pipe理器类 ?

Solutions Collecting From Web of "Android:如何使用下载pipe理器类?"

是否有可能使用我在这里find的android下载pipe理器类

是的,尽pipe这只是从Android API级别9(版本2.3)才可用。 下面是演示使用DownloadManager 的示例项目 。

使用DownloadManager类(GingerBread和更新版本)

GingerBread带来了一个新function,DownloadManager,它允许您轻松下载文件,并委托处理线程,stream等的辛勤工作,以系统。

首先,我们来看一个实用的方法:

 /** * @param context used to check the device version and DownloadManager information * @return true if the download manager is available */ public static boolean isDownloadManagerAvailable(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { return true; } return false; } 

方法的名字解释了这一切。 一旦你确定DownloadManager可用,你可以做这样的事情:

 String url = "url you want to download"; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDescription("Some descrition"); request.setTitle("Some title"); // in order for this if to run, you must use the android 3.2 to compile your app if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext"); // get download service and enqueue file DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); 

下载进度将显示在通知栏中。

 DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse("http://www.example.com/myfile.mp3"); DownloadManager.Request request = new DownloadManager.Request(uri); request.setTitle("My File"); request.setDescription("Downloading"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationUri(Uri.parse("file://" + folderName + "/myfile.mp3")); downloadmanager.enqueue(request);