crazydev
crazydev

Reputation: 575

How can I get the value from EventHandler to Background Service in Xamarin.Android

I am using the below codes to connect to BLE devices. My issue is that I want my service to listen to any changes that occur in the GattCallBack class when a device is connected or disconnected and show this as a local notification.

      public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
      {
                base.OnConnectionStateChange(gatt, status, newState);

                if(newState == ProfileState.Connected)
   }

How can I listen for any connectivity changes in the service below?

    [Service]
    public class DemoService : Service
    {


             public override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
                var t = new Thread (() => {
                        Log.Debug ("DemoService", "Doing work");
                        StopSelf ();
                }
                );
                t.Start ();
                return StartCommandResult.Sticky;
}

Upvotes: 1

Views: 175

Answers (1)

Leo Zhu
Leo Zhu

Reputation: 14956

You can declare a bluetooth connection method in the service, instantiate the service in the Activity and call the connection method, and then monitor the device in the service,and register the broadcast in the Activity to listen for the connection status issued by the service

in the service :

public bool Initialize() 
    {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) GetSystemService (Context.BluetoothService);
            if (mBluetoothManager == null) {
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.Adapter;
        if (mBluetoothAdapter == null) {
            return false;
        }

        return true;
    }

public bool Connect (String address)
    {
        if (mBluetoothAdapter == null || address == null) {
            return false;
        }

        if (mBluetoothDeviceAddress != null && address == mBluetoothDeviceAddress && mBluetoothGatt != null) {
            if (mBluetoothGatt.Connect ()) {
                mConnectionState = State.Connecting;
                return true;
            } else {
                return false;
            }
        }

        BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice (address);
        if (device == null) {
            Log.Warn (TAG, "Device not found.  Unable to connect.");
            return false;
        }
        mBluetoothGatt = device.ConnectGatt (this, false, new BGattCallback (this));
        mBluetoothDeviceAddress = address;
        mConnectionState = State.Connecting;
    }

class BGattCallback : BluetoothGattCallback
{
    YourService service;

    public  BGattCallback (YourService s)
    {
        service = s;
    }

    public override void OnConnectionStateChange (BluetoothGatt gatt, GattStatus status, ProfileState newState)
    {
        String intentAction;
        if (newState == ProfileState.Connected) {
            intentAction = BluetoothLeService.ACTION_GATT_CONNECTED;
            Intent intent = new Intent (intentAction);
            service.SendBroadcast (intent);
        } else if (newState == ProfileState.Disconnected) {
            intentAction = BluetoothLeService.ACTION_GATT_DISCONNECTED;
            Intent intent = new Intent (intentAction);
            service.SendBroadcast (intent);
        }
    }

in the activity:

protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.gatt_services_characteristics);
        mServiceManager = new ServiceManager (this);
        Intent gattServiceIntent = new Intent(this, typeof (YourService));
        BindService (gattServiceIntent, mServiceManager, Bind.AutoCreate);
   }

protected override void OnResume ()
    {
        base.OnResume ();

        //RegisterReceiver
    }

protected override void OnPause ()
    {
        base.OnPause ();
        //UnregisterReceiver;
    }

protected override void OnDestroy ()
    {
        base.OnDestroy ();
        //UnbindService;

    }
class ServiceManager : BroadcastReceiver
{   
    Activity _activity;

    public ServiceManager (Activity dca)
    {
        _activity= dca;
    }

    public override void OnReceive (Context context, Intent intent)
    {
        String action = intent.Action;

        if (BluetoothLeService.ACTION_GATT_CONNECTED == action) {
            //do Something
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED == action) {
            //do Something
        }
    }
}

That's the general direction,more accurate and specific can refer to : https://github.com/xamarin/monodroid-samples/tree/master/BluetoothLeGatt

Upvotes: 2

Related Questions