onReceive无法正常工作

时间:2016-09-07 11:21:51

标签: android android-download-manager

我有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()的{​​{1}}中调用

button。当我第一次点按onClickListener时,图片将被下载一次并且button消息显示一次,第二次点按Log时,图片将会显示下载了一次,但button消息显示了两次,这与我点击Log的情况一样多。为什么会这样?该如何修复?

1 个答案:

答案 0 :(得分:2)

之所以发生这种情况,是因为您多次注册接收器而未取消注册,因此您必须执行以下两项操作之一:

甚至仅在您的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);

}

OR 每次处理完下载文件时都会调用取消注册接收器:

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);

}