Create an IntentFilter in android that matches ALL intents

前端 未结 2 855
说谎
说谎 2021-01-02 01:25

Is it possible to create an IntentFilter in android that matches ALL intents that are Broadcasted on the phone (perhaps by way of using a BroadcastReceiver)? I.E. the ones I

2条回答
  •  醉酒成梦
    2021-01-02 02:03

    You can register a costume receiver for each event type that will hold a reference to a parent broadcast receiver and call its onReceive method

    class ChildBroadcastReceiver extends BroadcastReceiver {
    
        private BroadcastReceiver parent;
    
        public ChildBroadcastReceiver(BroadcastReceiver parent) {
            this.parent = parent;
        }
        @Override
        public void onReceive(Context context, Intent intent) {
            parent.onReceive(context, intent);
        }
    }
    

    Then you can register to all the possible events by using reflection:

    final BroadcastReceiver parent = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
               android.util.Log.d("GlobalBroadcastReceiver", "Recieved: " +   intent.getAction() + " " + context.toString());
          }
    };
    
    Intent intent = new Intent();
    for(Field field : intent.getClass().getDeclaredFields()) {
        int modifiers = field.getModifiers();
        if( Modifier.isPublic(modifiers) &&
            Modifier.isStatic(modifiers) &&
            Modifier.isFinal(modifiers) &&
            field.getType().equals(String.class)) {
    
                String filter = (String)field.get(intent);
                android.util.Log.d("GlobalBroadcastReceiver", "Registered: " + filter);
                application.registerReceiver(new ChildBroadcastReceiver(parent), new IntentFilter(filter));
            }
    }
    

提交回复
热议问题