I'm trying to find a way to detect the plugged/unplugged event on headphone Jack in Xamarin.Android. Is there a way to do it in this? and if it is, how can I implement that functionality?
Detect plugged & unplugged event on headphone jack in Xamarin.Android
254 Views Asked by Vahid Ahmadi At
3
There are 3 best solutions below
2

You have to write the code in xamarin.android file. Use broadcast receiver for implementation. In onReceive() you will get the intent as Intent.ACTION_HEADSET_PLUG.
Following pseudo code might help you,
public class MainActivity extends AppCompatActivity {
BroadcastReceiver broadcastReceiver;
boolean Microphone_Plugged_in = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
int iii;
if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
iii = intent.getIntExtra("state", -1);
if (iii == 0) {
Microphone_Plugged_in = false;
Toast.makeText(getApplicationContext(), "microphone not plugged in", Toast.LENGTH_LONG).show();
}
if (iii == 1) {
Microphone_Plugged_in = true;
Toast.makeText(getApplicationContext(), "microphone plugged in",
Toast.LENGTH_LONG).show();
}
}
}
};
IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(broadcastReceiver, receiverFilter);
}
}
2

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionHeadsetPlug })]
public class HeadsetPlugBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
String action = intent.Action;
if (Intent.ActionHeadsetPlug.Equals(action))
{
var state = intent.GetIntExtra("state", -1);
if (state == 0)
{
// Plugged out
}
if (state == 1)
{
// Plugged in
}
}
}
}
you can try to convert java code into c#, for example:
And usage:
and initialize value in method
OnCreate
of your activity:And
RegisterReceiver
andUnregisterReceiver
by override methodOnResume
andOnPause
For more, you can check thread: Detecting whether a headset is plugged into an Android device or not.
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/broadcast-receivers