我正在编写一个应用程序,其中我想检测下载是否已启动并检索正在下载的文件的URI,然后从下载管理器取消下载。我正在这样做,以便我可以在其他地方发送此URI。
问题是我可以通过查询下载管理器来检测下载开始的时间,但是下载管理器中是否有方法或常量变量,我也可以从中获取正在下载的文件的URL
答案 0 :(得分:3)
好吧回答你自己的问题很奇怪,但我终于想出了如何做到这一点。 android.app中有一个DownloadManager类,它存储了所有启动的http下载列表及其状态。这些可以根据下载是“RUNNING”,“PENDING”,“PAUSED”等过滤掉。
此列表可以读入游标,结果的一列是“COLUMN_URI”,这是从中下载文件的URL。我使用它的示例代码如下所示:
public void readDownloadManager() {
DownloadManager.Query query = null;
DownloadManager downloadManager = null;
Cursor c = null;
try {
query = new DownloadManager.Query();
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
//Just for testing I initiated my own download from this url. When an http
// reuest for this url is made, since download is taking place, it gets saved in
// the download manager.
Request request = new Request(Uri.parse("http://ocw.mit.edu/courses" +
"/aeronautics-and-astronautics/16-100-aerodynamics-fall-2005" +
"/lecture-notes/16100lectre1_kvm.pdf"));
downloadManager.enqueue(request);
query.setFilterByStatus(DownloadManager.STATUS_PENDING);
c = downloadManager.query(query);
if(true){
int statusColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int urlColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_URI);
long downloadProcessIdColumnNo = c.getColumnIndex(DownloadManager.COLUMN_ID);
Log.d("Column Count", ((Integer)c.getCount()).toString());
if(c.getCount() > 0){
String url="";
c.moveToLast();
if(c.isLast()){
url = c.getString(urlColumnIndex);
downloadManager.remove(downloadProcessIdColumnNo);
Log.d("Count after remove", ((Integer)c.getCount()).toString());
}
Log.d("After", "Stopped Working");
//Here I am sending the url to another activity, where I can work with it.
Intent intent = new Intent(EasyUploadMainMenu.this, EasyUploadActivity.class);
Bundle b = new Bundle();
b.putString("url", url);
intent.putExtras(b);
startActivity(intent);
Log.d("url:", url);
}
}
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}