BroadcastReceiver with multiple filters or multiple BroadcastReceivers?

后端 未结 2 811
误落风尘
误落风尘 2020-12-12 14:36

I have an Android Activity that needs to catch two different broadcasts. My current approach is to have a single BroadcastReceiver within the Activity and catch

相关标签:
2条回答
  • 2020-12-12 15:03

    For every action , create IntentFilter and register it.

    @Override
    protected void onResume() {
    
        super.onResume();
    
        BroadcastListener receiver = new BroadcastListener();
    
        // Register the filter for listening broadcast.
        IntentFilter filterRefresh = new IntentFilter(Params.INTENT_REFRESH);
        IntentFilter filterUpdate = new IntentFilter(Params.INTENT_UPDATE);
    
        registerReceiver(receiver, filterRefresh);
        registerReceiver(receiver, filterUpdate);
    } 
    
    
    
    private class BroadcastListener extends BroadcastReceiver {
        public void onReceive(Context ctx, Intent intent) {
    
            if (intent.getAction().equals(Params.INTENT_UPDATE)) {
                update();
            } else if(intent.getAction().equals(Params.INTENT_REFRESH)) {
                refresh();
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-12 15:29

    instead, you may provide two different intent filters:

    filter for refresh only

    IntentFilter filterRefresh = new IntentFilter(Params.INTENT_REFRESH);
    

    filter for refresh and update

    IntentFilter filterRefreshUpdate = new IntentFilter();
    filterRefreshUpdate.addAction(Params.INTENT_REFRESH);
    filterRefreshUpdate.addAction(Params.INTENT_UPDATE);
    

    now you may switch between intent filters by registering and un-registering the desired one but your receiver's implementation would be same

    0 讨论(0)
提交回复
热议问题