Во-первых, можно создать BroadcastReceiver
для прослушивания состояния Bluetooth, например:
public class BluetoothStateBroadcastReceive : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
string action = intent.Action;
BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
switch (action)
{
case BluetoothDevice.ActionAclConnected:
Toast.MakeText(context, "BluetoothDevice:" + device.Name + "Connected", ToastLength.Long).Show();
break;
case BluetoothDevice.ActionAclDisconnected:
Toast.MakeText(context, "BluetoothDevice:" + device.Name + "Disconnected", ToastLength.Short).Show();
break;
case BluetoothAdapter.ActionStateChanged:
Toast.MakeText(context, "BluetoothDevice:" + device.Name + "Changed", ToastLength.Short).Show();
//int blueState = intent.GetIntExtra(BluetoothAdapter.ExtraState, 0);
//switch (blueState)
//{
// case BluetoothAdapter.STATE_OFF:
// Toast.MakeText(context, "off", ToastLength.Short).Show();
// break;
// case BluetoothAdapter.STATE_ON:
// Toast.MakeText(context, "on", ToastLength.Short).Show();
// break;
//}
break;
}
}
}
А в service
вы можете зарегистрировать его:
public class BluetoothService : Service
{
private BluetoothStateBroadcastReceive mReceive;
public BluetoothService()
{
}
public BluetoothService(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
registerBluetoothReceiver();
return base.OnStartCommand(intent, flags, startId);
}
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
private void registerBluetoothReceiver()
{
if (mReceive == null)
{
mReceive = new BluetoothStateBroadcastReceive();
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.AddAction(BluetoothAdapter.ActionStateChanged);
intentFilter.AddAction(BluetoothDevice.ActionAclConnected);
intentFilter.AddAction(BluetoothDevice.ActionAclDisconnected);
//intentFilter.AddAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
//intentFilter.AddAction("android.bluetooth.BluetoothAdapter.STATE_ON");
RegisterReceiver(mReceive, intentFilter);
}
public override void OnDestroy()
{
unregisterBluetoothReceiver();
base.OnDestroy();
}
private void unregisterBluetoothReceiver()
{
if (mReceive != null)
{
UnregisterReceiver(mReceive);
mReceive = null;
}
}
}
Затем вы можете попробовать это там, где хотите. При использовании service
вы можете обратиться к этому документу .