Create an IntentFilter in android that matches ALL intents

前端 未结 2 831
说谎
说谎 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 01:54

    You said it yourself, the documentation quite clearly specifies how intent filters function and that this is not possible to receive all broadcasts.

    Neither this nor retrieving task information is something that is supported by the APIs made public in the Android SDK.

    0 讨论(0)
  • 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));
            }
    }
    
    0 讨论(0)
提交回复
热议问题