Hi i am working on an application that generate an event when ever the headphone is removed from the mobile phone. I have created a broadcast receiver with receive method as
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
Log.i("Broadcast Receiver", "Hello");
if( (action.compareTo(Intent.ACTION_HEADSET_PLUG)) == 0) //if the action match a headset one
{
int headSetState = intent.getIntExtra("state", 0); //get the headset state property
int hasMicrophone = intent.getIntExtra("microphone", 0);//get the headset microphone property
if( (headSetState == 0) && (hasMicrophone == 0)) //headset was unplugged & has no microphone
{
//do whatever
}
}
}
Calling this method as follows
IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
HeadSetBroadCastReceiver receiver = new HeadSetBroadCastReceiver();
registerReceiver( receiver, receiverFilter );
also i have register this in manifest as
<receiver android:name=".HeadsetBroadCastReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_HEADSET_PLUG"/>
</intent-filter>
</receiver>
and permission
But this doesnot works can anyone guide me through this?
To stop receiving broadcasts, call unregisterReceiver(android. content. BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.
A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.
it's tricky point but you can use BroadCast as the Following working well with me in your Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new HeadSetReceiver();
}
and in onResume() Method register your Broadcast
public void onResume() {
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(myReceiver, filter);
super.onResume();
}
then Declare your BroadCast in your Activity
private class HeadSetReceiver extends BroadcastReceiver {
@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;
}
}
}
}
Hope it's Help ,,,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With