Reputation: 367
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>
Upvotes: 4
Views: 5204
Reputation: 11701
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 );
Upvotes: 2
Reputation: 1981
If the minimum SDK version of your application is LOLLIPOP
, it is recommended to refer to the AudioManager
constant AudioManager.ACTION_HEADSET_PLUG
in your receiver registration code instead.
Upvotes: 4