java - Android - 多次调用 DownloadManager/BroadcastReceiver

标签 java android broadcastreceiver download-manager android-download-manager

我在我的应用程序中使用 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 完成,然后一个新的 toast b.mp3 完成...

我该如何防止这种情况发生?谢谢。

最佳答案

您每次下载文件时都会注册一个BroadcastReceiver。这意味着,第二次下载文件时,您将注册两个接收者。您可能应该使用 unregisterReceiver() 取消注册它们工作完成后(可能在 onReceive() 中)。

关于java - Android - 多次调用 DownloadManager/BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20986245/

相关文章:

java - 是否可以在不调用 Cyc 服务器的情况下生成 Cyc KBAPI 'constants'?

java - DataOutputStream 未清空缓冲区

android - 在 ListView 的项目点击没有响应

android - 在 Android 中使用 BroadcastReceiver、TimerTask 和 AsyncTask 每两分钟发送一封电子邮件的最佳方式

java - CONNECTIVITY_ACTION 广播接收器不工作

java - 使用 Jackson 序列化和反序列化任意值

java - hibernate 检测级联插入

android - 使用 SearchView 将附加数据传递给 SearchActivity

android - 如何在 ContactsContract 中创建用户配置文件?

java - 将数据传递给已经具有来自 Activity 的 Intent 过滤器的广播接收器