我不明白这段代码有什么问题。
Listener 在活动的 onCreate 中:
private BroadcastReceiver receiver;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("MAIN onCreate: ", "It is never shown.");
}
};
}
寄存器在activity的onResumen中:
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter("receiveMyService"));
}
发件人在一个按钮中,我可以看到日志运行良好,但 test 的值为 false:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent("receiveMyService");
Boolean test = LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Log.e("Button", "It works but test is always false: " + test);
return true;
}
return super.onOptionsItemSelected(item);
}
为什么 BroadcastReceiver - onReceive 的代码永远不会运行?