onReceive 无法正常工作

onReceive does'n work properly

我有一个 download manager 可以在单击 button 时下载图像。在 broadcast receivers 的帮助下,我会做到这一点。 下面是我的代码:

public void myDownloadManager(){

        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                String action = intent.getAction();

                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(enqueue);
                    Cursor c = dm.query(query);
                    if (c.moveToFirst()) {

                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);

                        if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
//                            download finished successfully
                            Log.e("count downloads", "counting");
                            db.insertDownloadsRows(image_id);

                        }
                    }
                }
            }
        };

        getActivity().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    }

    public void downloadImage(){

        myDownloadManager();

        dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("some uri"));
        request.setDestinationInExternalPublicDir("some directory", name);
        enqueue = dm.enqueue(request);


    }

downloadImage()buttononClickListener中被调用。当我第一次点击 button 时,图像将被下载一次并显示一次 Log 消息,当我第二次点击 button 时,图像将被下载了一次,但 Log 消息出现了两次,只要我点击 button,就会发生这种情况。为什么会这样?应该如何修复?

发生这种情况是因为您在没有注销的情况下多次注册接收器,因此您必须执行以下两项操作之一:

even 仅注册一次接收器,例如在您的 onCreate() 方法中(这绝对是更好的解决方案):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.videoview);

    myDownloadManager();
}

public void downloadImage(){

    dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("some uri"));
    request.setDestinationInExternalPublicDir("some directory", name);
    enqueue = dm.enqueue(request);

}

每次处理完下载文件后调用unregister receiver:

public void downloadImage(){

    // Un-registering the receiver
    unregisterReceiver(receiver);

    myDownloadManager();

    dm = (DownloadManager) getActivity().getSystemService(getActivity().DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("some uri"));
    request.setDestinationInExternalPublicDir("some directory", name);
    enqueue = dm.enqueue(request);

}