广播动态注册,“ onReceive”未调用

时间:2019-07-03 22:24:20

标签: android broadcastreceiver android-manifest intentfilter

这是我的简单测试代码,在该代码中,我尝试动态注册接收者,但是它不起作用。

public class MainActivity extends AppCompatActivity {
    MyBroadacast broadacast;
    IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("xyz");
        this.registerReceiver(broadacast, intentFilter);

        Intent intent = new Intent("xyz");
        intent.putExtra("some_text", "text");
        this.sendBroadcast(intent);

        broadacast = new MyBroadacast() {
            @Override
            public void onReceive(Context context, Intent intent) {
                super.onReceive(context, intent);
                String g = intent.getStringExtra("some_text");
                Log.d("ololo", "onReceive " + g);
            }
        };
    }
}

它应该显示日志消息,但不显示。

1 个答案:

答案 0 :(得分:1)

只需更改代码顺序

  1. 初始化广播
  2. 初始化intentFilter
  3. 发送广播

首先初始化广播

broadacast = new MyBroadacast() {
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            String g = intent.getStringExtra("some_text");
            Log.d("ololo", "onReceive " + g);
        }
    };

然后初始化intentFilter

  IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("xyz");
        this.registerReceiver(broadacast, intentFilter);

然后发送广播

Intent intent = new Intent("xyz");
    intent.putExtra("some_text", "text");
    this.sendBroadcast(intent);