这是我的简单测试代码,在该代码中,我尝试动态注册接收者,但是它不起作用。
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);
}
};
}
}
它应该显示日志消息,但不显示。
答案 0 :(得分:1)
只需更改代码顺序
首先初始化广播
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);