繁体   English   中英

使用LocalBroadcastManager注册BroadcastReceiver时,不会调用onReceive

[英]onReceive not being called when BroadcastReceiver is registered using LocalBroadcastManager

当我的应用程序开始使用DownloadManager时,我创建了一个BroadcastReceiver来接收ACTION_DOWNLOAD_COMPLETE 因为我只想在从我的应用程序开始下载时捕获ACTION_DOWNLOAD_COMPLETE ,所以我使用了LocalBroadcastManager

onReceiver根本没有被调用。 DownloadManager应用程序显示下载已完成但未触发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();
    }

DownloadReciever

    @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因为我只有在我的应用程序开始下载时才需要跟踪下载完成操作。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM