Search code examples
androidandroid-intentintentfilter

FC when trying an Intent of an ACTION_HEADSET_PLUG


I'm trying the next code.

IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
Intent headsetState = MainActivity.this.registerReceiver(null, filter);
int state = headsetState.getIntExtra("state", -1);
String name = headsetState.getStringExtra("name");

My problem is when I try the method when the phone just started up, the Intent value of headsetState is NULL, and the app closes. But If I have plugged/unplugged a earphones to the phone, the app seems to work, headsetState has a value.

My question is why this "Intent" is NULL at first, should have a value, no?

Thanks for your advices.


Solution

  • From the documentation, registerReceiver returns

    "The first sticky intent found that matches filter, or null if there are none."

    Since there was no sticky intent found, it returns null. You're not using it correctly. The return value is intended to help you capture any sticky broadcasts that arrived before you registered your receiver, and the registered receiver (which you didn't provide) would handle future events in onReceive().