Exemplo n.º 1
0
        private async void Start()
        {
            startButton.Enabled = false;
            status = FindViewById <TextView>(Resource.Id.output);
            var devicePicker = FindViewById <Spinner>(Resource.Id.device_picker);
            var id           = devicePicker.SelectedItem.ToString();
            var btAddress    = devices[id];

            if (btAddress == null)
            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.AccessFineLocation }, 1000);
                    return;
                }
                if (launched)
                {
                    return;
                }

                launched = true;
                listener = new NmeaParser.SystemNmeaDevice(ApplicationContext);
            }
            else //Bluetooth
            {
                try
                {
                    status.Text = "Opening bluetooth...";
                    var            adapter     = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;
                    var            bt          = Android.Bluetooth.BluetoothAdapter.DefaultAdapter.GetRemoteDevice(btAddress);
                    Java.Util.UUID SERIAL_UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for Serial Device Service
                    socket = bt.CreateRfcommSocketToServiceRecord(SERIAL_UUID);
                    try
                    {
                        await socket.ConnectAsync();
                    }
                    catch (Java.IO.IOException)
                    {
                        // This sometimes fails. Use fallback approach to open socket
                        // Based on https://stackoverflow.com/a/41627149
                        socket.Dispose();
                        var m = bt.Class.GetMethod("createRfcommSocket", new Java.Lang.Class[] { Java.Lang.Integer.Type });
                        socket = m.Invoke(bt, new Java.Lang.Object[] { 1 }) as Android.Bluetooth.BluetoothSocket;
                        socket.Connect();
                    }
                    listener = new NmeaParser.StreamDevice(socket.InputStream);
                }
                catch (System.Exception ex)
                {
                    socket?.Dispose();
                    socket       = null;
                    status.Text += "\nError opening Bluetooth device:\n" + ex.Message;
                }
            }

            if (listener != null)
            {
                listener.MessageReceived += Listener_MessageReceived;
                status.Text += "\nOpening device...";
                await listener.OpenAsync();

                status.Text        += "\nConnected!";
                startButton.Enabled = !(stopButton.Enabled = true);
            }
            else
            {
                startButton.Enabled = !(stopButton.Enabled = false);
            }
        }
        public BluetoothPrinterService()
        {
            BluetoothLowEnergy ble = new BluetoothLowEnergy();



            Android.Bluetooth.BluetoothAdapter ba = null;
            try
            {
                ba = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;

                if (null != ba)
                {
                    try
                    {
                        Android.Bluetooth.State state = ba.State;
                    }
                    catch (Exception exc)
                    {
                        Android.Widget.Toast.MakeText
                        (
                            Android.App.Application.Context,
                            "Add bluetooth permission",
                            Android.Widget.ToastLength.Long
                        ).Show();
                    }
                }
            }
            catch (Exception exc)
            {
                string msg = "if this fails - AndroidManifest.xml";
                LoggerService.WriteLine(msg);
            }

            if (ba == null)
            {
                LoggerService.WriteLine("BluetoothAdapter == null");
                return;
            }

            if (!ba.IsEnabled)
            {
                LoggerService.WriteLine("Bluetooth adapter is not enabled.");
            }

            foreach (var bd in ba.BondedDevices)
            {
                LoggerService.WriteLine(bd.Name);
            }
            string device_name = "Qsprinter";

            Android.Bluetooth.BluetoothDevice device =
                (
                    from bd in ba.BondedDevices
                    where bd.Name == device_name
                    select bd
                ).FirstOrDefault();

            if (device == null)
            {
                LoggerService.WriteLine("Bluetooth device not found = " + device_name);
            }

            Android.OS.ParcelUuid[] uuids = device.GetUuids();
            string uuid =
                uuids[0].ToString()
                //Guid.NewGuid().ToString()
            ;

            _socket = device
                      .CreateInsecureRfcommSocketToServiceRecord(Java.Util.UUID.FromString(uuid))
                      //.CreateRfcommSocketToServiceRecord (Java.Util.UUID.FromString (uuid))
            ;


            try
            {
                _socket.Connect();
                if (_socket.IsConnected)
                {
                    LoggerService.WriteLine("Bluetooth socket connected ");
                }
            }
            catch (Exception exc)
            {
//			[BluetoothUtils] isSocketAllowedBySecurityPolicy start : device null
//			[BluetoothSocket] GlobalConfig.GLOBALCONFIG_BT_IT_POLICY_FEATURE = true
//			[BluetoothAdapter] getBluetoothService() called with no BluetoothManagerCallback
//			[BluetoothSocket] connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[78]}
            }

            byte[] data_bytes = System.Text.Encoding.UTF8.GetBytes("Bluetooth created");

            // Write data to the device
            //await
            try
            {
                _socket.OutputStream.WriteAsync(data_bytes, 0, data_bytes.Length);
            }
            catch (Exception exc)
            {
            }

            return;
        }