我正在使用DownloadManager来处理我的应用程序中的下载,我想在下载完成时通知用户。
我正在使用效果良好的下列代码
public void downloaddownload(View v){
View v2 = (View) v.getParent();
TextView urlView = (TextView) v2.findViewById(R.id.url);
String urlString = (String) urlView.getText().toString();
TextView artistView2 = (TextView) v2.findViewById(R.id.artist);
final String artistString = (String) artistView2.getText().toString();
TextView titleView2 = (TextView) v2.findViewById(R.id.title);
final String titleString = (String) titleView2.getText().toString();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlString));
request.setDescription(titleString);
request.setTitle(artistString);
// 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_MUSIC + "/folder", titleString + " - " + artistString + ".mp3");
Toast.makeText(mainContext, "Downloading " + titleString + " - " + artistString, Toast.LENGTH_SHORT).show();
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(mainContext, "Download \" " + titleString + " - " + artistString + "\" completed", Toast.LENGTH_LONG).show();
}
};
registerReceiver(onComplete, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
问题在于,以前的下载也会调用onReceive方法。
假设我下载a.mp3,b.mp3和c.mp3,当a.mp3完成后我收到a.mp3完成,当b.mp3完成后我收到a.mp3完成,然后是新的吐司b.mp3已经完成......
我怎么能阻止这个?谢谢。
答案 0 :(得分:9)
Yo每次下载文件时都会注册BroadcastReceiver
。这意味着,第二次下载文件时,您将注册两个接收器。您应该在工作完成后使用unregisterReceiver()
取消注册它们(可能在onReceive()
中)。
答案 1 :(得分:1)
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(downloadId);
Cursor cur = manager.query(query);
if (cur.moveToFirst()) {
int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
titleString=cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_TITLE));}
你应该使用它来获取个人下载的标题字符串。因为每个下载都有自己的ID。我知道答案为时已晚,但将来可能对其他人有所帮助......