簡體   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