3

当我的应用开始BroadcastReceiver使用. 因为我只想在从我的应用程序开始下载时捕获,所以我使用了.ACTION_DOWNLOAD_COMPLETEDownloadManagerACTION_DOWNLOAD_COMPLETELocalBroadcastManager

onReceiver根本没有被调用。DownloadManagerapp 显示下载完成但未onReceive触发。当我使用registerReceiver它时,它按预期工作。但这会让应用程序得到通知,即使下载是由其他应用程序开始的。所以 LocalBroadcastManager 是需要的。

主要活动

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        downloadReceiver = new DownloadReceiver();

        LocalBroadcastManager.getInstance(this).registerReceiver(downloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));           

        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        if(FileHelper.isStorageAvailable()) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/image.jpg"));
            downloadManager.enqueue(request);
        }
    }
    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(downloadReceiver);
        super.onPause();
    }

下载接收器

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            Cursor c = downloadManager.query(query);

            if (c.moveToFirst()) {
                int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {                        
                    String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));                 
                    Toast.makeText(context, title, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

它根本不onRecieve应该调用。指出我在这里做错了什么。现在被困在这里很长时间了。我无法使用registerReceiver,因为只有在我的应用开始下载时才需要跟踪下载完成操作。

4

1 回答 1

3

因为我只想在从我的应用程序开始下载时捕获 ACTION_DOWNLOAD_COMPLETE,所以我使用了 LocalBroadcastManager。

那是行不通的。DownloadManager在单独的过程中进行下载,它将使用系统广播。您可以接收的唯一LocalBraodcastManager广播是您通过广播LocalBroadcastManager的广播。

于 2015-03-02T18:06:29.403 回答