Reputation: 310
I don't get what is wrong with this code.
The Listener is in the onCreate of the activity:
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.");
}
};
}
The register is in the onResumen of the activity:
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter("receiveMyService"));
}
The sender is in a button and I can see the Log is working perfectly, but with the value of test as 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);
}
Why the code of the BroadcastReceiver - onReceive never runs?
Upvotes: 0
Views: 422
Reputation: 723
Because you register a BroadcastReceiver
not a LocalBroadcastReceiver
replace this:
registerReceiver(receiver, new IntentFilter("receiveMyService"));
with this
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("receiveMyService"));
Upvotes: 1