Issues with ACTION_HEADSET_PLUG broadcast in Android

纵然是瞬间 提交于 2019-12-04 19:36:57

The code is wrong!

"state" and "microphone" is integer, not string. So the code should be modified as following:

    int st = intent.getIntExtra("state" , -1);
    String nm = intent.getStringExtra("name");
    int mic = intent.getIntExtra("microphone", -1);
    String all = "st="+Integer.toString(st)+" nm="+nm+" mic="+Integer.toString(mic);

It works!

Broadcast comes when activity is started (not expected)

It's in the documentation of registerReceiver:

The system may broadcast Intents that are "sticky" -- these stay around after the broadcast as finished, to be sent to any later registrations. If your IntentFilter matches one of these sticky Intents, that Intent will be returned by this function and sent to your receiver as if it had just been broadcast.

My guess as to the reason would be that your Activity has a chance to get the current state for such "sticky" broadcasts right after you have registered for it.

I'm currently working on an app with 2 devices that need to receive ACTION_HEADSET_PLUG, and it seems there are devices that do not send this system broadcast (i'm not receiving it on my tablet, but am receiving it on my phone), so one could conclude that, after registering for this broadcast and it hasn't been received at least once, then the device doesn't support sending it. I haven't tested if this applies to other system broadcasts as well, but i would imagine so.

Silly me, the problem is slightly different - 'state' and 'name' are there without 'microphone'. Another thing - 'state' is 0 and 1 for headphones, and 0 and 3 for headset. Super weird...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!