简体   繁体   中英

android: Headset plug listener

public class HeadsetIntentReceiver extends BroadcastReceiver {
    private String TAG = "HeadSet";

    public HeadsetIntentReceiver() {
        Log.d(TAG, "Created");
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
            int state = intent.getIntExtra("state", -1);
            switch(state) {
                case(0):
                    Log.d(TAG, "Headset unplugged");
                    break;
                case(1):
                    Log.d(TAG, "Headset plugged");
                    break;
                default:
                    Log.d(TAG, "Error");
            }
        }
    }
}

Here's my code for listening for headphone plug, I initiated this from a Service class, but every time I plug and unplug it, nothing appears on the Logcat, any ideas?

AndriodManifest.xml

<service android:name="com.jason.automator.HeadphoneJackListenerService" />
        <receiver android:name=".HeadsetIntentReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.HEADSET_PLUG" />
            </intent-filter>
        </receiver>

如果应用程序的最低SDK版本是LOLLIPOP ,建议您在接收器注册码中引用AudioManager常量AudioManager.ACTION_HEADSET_PLUG

If you haven't registered your receiver in manifest you can do like below

<receiver android:name=".HeadsetIntentReceiver" > 
    <intent-filter> 
        <action android:name="android.intent.action.HEADSET_PLUG" /> 
    </intent-filter> 
</receiver> 

Also you can register it dynamically.

When OS send this "HEADSET_PLUG" intent, OS set the flag "Intent.FLAG_RECEIVER_REGISTERED_ONLY" . That's why may be your code not working. So try registering dynamically like below in Activity or Service class instead of "AndroidManifest" things.

So try below code,

    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    HeadsetIntentReceiver receiver = new HeadsetIntentReceiver();
    registerReceiver( receiver, receiverFilter );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM