Пример #1
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Setup the window
			RequestWindowFeature (WindowFeatures.IndeterminateProgress);
			SetContentView (Resource.Layout.device_list);
			
			// Set result CANCELED incase the user backs out
			SetResult (Result.Canceled);

			// Initialize the button to perform device discovery			
			var scanButton = FindViewById<Button> (Resource.Id.button_scan);
			scanButton.Click += (sender, e) => {
				DoDiscovery ();
				(sender as View).Visibility = ViewStates.Gone;
			};
			
			// Initialize array adapters. One for already paired devices and
			// one for newly discovered devices
			pairedDevicesArrayAdapter = new ArrayAdapter<string> (this, Resource.Layout.device_name);
			newDevicesArrayAdapter = new ArrayAdapter<string> (this, Resource.Layout.device_name);
			
			// Find and set up the ListView for paired devices
			var pairedListView = FindViewById<ListView> (Resource.Id.paired_devices);
			pairedListView.Adapter = pairedDevicesArrayAdapter;
			pairedListView.ItemClick += DeviceListClick;
			
			// Find and set up the ListView for newly discovered devices
			var newDevicesListView = FindViewById<ListView> (Resource.Id.new_devices);
			newDevicesListView.Adapter = newDevicesArrayAdapter;
			newDevicesListView.ItemClick += DeviceListClick;
			
			// Register for broadcasts when a device is discovered
			receiver = new Receiver (this);
			var filter = new IntentFilter (BluetoothDevice.ActionFound);
			RegisterReceiver (receiver, filter);
			
			// Register for broadcasts when discovery has finished
			filter = new IntentFilter (BluetoothAdapter.ActionDiscoveryFinished);
			RegisterReceiver (receiver, filter);
			
			// Get the local Bluetooth adapter
			btAdapter = BluetoothAdapter.DefaultAdapter;
			
			// Get a set of currently paired devices
			var pairedDevices = btAdapter.BondedDevices;
			
			// If there are paired devices, add each one to the ArrayAdapter
			if (pairedDevices.Count > 0) {
				FindViewById<View> (Resource.Id.title_paired_devices).Visibility = ViewStates.Visible;
				foreach (var device in pairedDevices) {
					pairedDevicesArrayAdapter.Add (device.Name + "\n" + device.Address);
				}
			} else {
				String noDevices = Resources.GetText (Resource.String.none_paired);
				pairedDevicesArrayAdapter.Add (noDevices);	
			}
			
		}
Пример #2
0
		public Adapter ()
		{
			var appContext = Application.Context;
			// get a reference to the bluetooth system service
			this._manager = (BluetoothManager) appContext.GetSystemService("bluetooth");
			this._adapter = this._manager.Adapter;

			if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
			{
				this.setLollipopProperty();
			}

			this._gattCallback = new GattCallback (this);

			this._gattCallback.DeviceConnected += (object sender, DeviceConnectionEventArgs e) => {
				Console.WriteLine("Device Connected: "+ e.Device.Name);

				this._connectedDevices.Add ( e.Device);
				this.DeviceConnected (this, e);
			};

			this._gattCallback.DeviceDisconnected += (object sender, DeviceConnectionEventArgs e) => {
				// TODO: remove the disconnected device from the _connectedDevices list
				// i don't think this will actually work, because i'm created a new underlying device here.
				if(this._connectedDevices.Contains(e.Device))
				{
					this._connectedDevices.Remove(e.Device);
				}
				this.DeviceDisconnected (this, e);
			};

		}
Пример #3
0
 public void EnableIfNeeded(BluetoothAdapter adapter)
 {
     if (!adapter.IsEnabled)
     {
         adapter.Enable();
     }
 }
Пример #4
0
        public Adapter()
        {
            ScanTimeout = 10000;

            DeviceOperationRegistry = new Dictionary<string, IDevice>();
            ConnectedDeviceRegistry = new Dictionary<string, IDevice>();

            var appContext = Android.App.Application.Context;
            // get a reference to the bluetooth system service
            this._manager = (BluetoothManager)appContext.GetSystemService(Context.BluetoothService);
            this._adapter = this._manager.Adapter;


            var bondStatusBroadcastReceiver = new BondStatusBroadcastReceiver();
            Application.Context.RegisterReceiver(bondStatusBroadcastReceiver,
                new IntentFilter(BluetoothDevice.ActionBondStateChanged));

            //forward events from broadcast receiver
            bondStatusBroadcastReceiver.BondStateChanged += (s, args) =>
            {
                this.DeviceBondStateChanged(this, args);
            };

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                _api21ScanCallback = new Api21BleScanCallback(this);
            }
        }
Пример #5
0
 //--------------------------------------------------------------
 // CONSTRUCTORS
 //--------------------------------------------------------------
 public BluetoothManager()
 {
     _deviceAddress = string.Empty;
     _handler = new MyHandler ();
     _bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
     _state = StateEnum.None;
 }
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			ActionBar.SetTitle (Resource.String.title_devices);

			mHandler = new Handler ();

			// Use this check to determine whether BLE is supported on the device.  Then you can
			// selectively disable BLE-related features.
			if (!PackageManager.HasSystemFeature (Android.Content.PM.PackageManager.FeatureBluetoothLe)) {
				Toast.MakeText (this, Resource.String.ble_not_supported, ToastLength.Short).Show ();
				Finish ();
			}

			// Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
			// BluetoothAdapter through BluetoothManager.
			BluetoothManager bluetoothManager = (BluetoothManager) GetSystemService (Context.BluetoothService);
			mBluetoothAdapter = bluetoothManager.Adapter;

			// Checks if Bluetooth is supported on the device.
			if (mBluetoothAdapter == null) {
				Toast.MakeText (this, Resource.String.error_bluetooth_not_supported, ToastLength.Short).Show();
				Finish();
				return;
			}
		}
Пример #7
0
        public Adapter(Context appContext)
        {
            ScanTimeout = TimeSpan.FromSeconds(10); // default timeout is 10 seconds
            _appContext = appContext;
            // get a reference to the bluetooth system service
            this._manager = appContext.GetSystemService("bluetooth").JavaCast<BluetoothManager>();
            this._adapter = this._manager.Adapter;

            this._gattCallback = new GattCallback(this);

            this._gattCallback.DeviceConnected += (object sender, DeviceConnectionEventArgs e) =>
            {
                if (ConnectedDevices.Find((BluetoothDevice)e.Device.NativeDevice) == null)
                {
                    _connectedDevices.Add(e.Device);
                    this.DeviceConnected(this, e);
                }
            };

            this._gattCallback.DeviceDisconnected += (object sender, DeviceConnectionEventArgs e) =>
            {
                var device = ConnectedDevices.Find((BluetoothDevice)e.Device.NativeDevice);
                if (device != null)
                {
                    _connectedDevices.Remove(device);
                    this.DeviceDisconnected(this, e);
                }
            };
        }
Пример #8
0
        public BluetoothHub(BluetoothAdapter adapter)
        {
            this.adapter = adapter;

            this.OpenSettings = new Command(
                o => o.StartActivityForResult(new Android.Content.Intent(BluetoothAdapter.ActionRequestEnable)),
                o => true
                );
        }
		protected BluetoothLEManager ()
		{
			var appContext = Android.App.Application.Context;
			// get a reference to the bluetooth system service
			this._manager = (BluetoothManager) appContext.GetSystemService("bluetooth");
			this._adapter = this._manager.Adapter;

			this._gattCallback = new GattCallback (this);
		}
Пример #10
0
		public DroidToothReactive ()
		{
			var appContext = Android.App.Application.Context;

			// get a reference to the bluetooth system service
			this.Manager = (BluetoothManager) appContext.GetSystemService("bluetooth");
			this.Adapter = this.Manager.Adapter;

			BroodSubject = new Subject<BroodtoothDevice> ();
		}
Пример #11
0
        internal AndroidBthRadio(Android.Bluetooth.BluetoothAdapter adapter)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException("adapter");
            }
            _adapter = adapter;
            string addrS = _adapter.Address;

            _addr = AndroidBthUtils.ToBluetoothAddress(addrS);
        }
Пример #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BluetoothLE.Droid.Adapter"/> class.
        /// </summary>
        public Adapter()
        {
            var appContext = Android.App.Application.Context;
            _manager = (BluetoothManager)appContext.GetSystemService("bluetooth");
            _adapter = _manager.Adapter;

            _callback = new GattCallback();
            _callback.DeviceConnected += BluetoothGatt_DeviceConnected;
            _callback.DeviceDisconnected += BluetoothGatt_DeviceDisconnected;

            ConnectedDevices = new List<IDevice>();
        }
Пример #13
0
		private void CheckBt() {
			mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

			if (!mBluetoothAdapter.Enable()) {
				Toast.MakeText(this, "Bluetooth Desactivado",
					ToastLength.Short).Show();
			}

			if (mBluetoothAdapter == null) {
				Toast.MakeText(this,
					"Bluetooth No Existe o esta Ocupado", ToastLength.Short)
					.Show();
			}
		}
Пример #14
0
        public bool StartPrint(string text,int noofcopy,ref string errmsg)
        {
            bool isPrinted = false;
            mBluetoothAdapter=null;
            mmSocket=null;
            mmDevice = null;
            FindBTPrinter ();
            if (mmDevice != null) {
                isPrinted =PrintToDevice (text, noofcopy);
            }
            errmsg = msg;

            return isPrinted;
        }
Пример #15
0
		public const int STATE_CONNECTED = 3;  // now connected to a remote device

		/// <summary>
		/// Constructor. Prepares a new BluetoothChat session.
		/// </summary>
		/// <param name='context'>
		/// The UI Activity Context.
		/// </param>
		/// <param name='handler'>
		/// A Handler to send messages back to the UI Activity.
		/// </param>
		public BluetoothChatService (Context context, Handler handler)
		{
			_adapter = BluetoothAdapter.DefaultAdapter;
			_handler = handler;
			for(int i =0; i<SIZE; i++) {
				_state[i] = STATE_NONE;
			}

			for (int i = 0; i < SIZE; i++) {

				connectThread [i] = null;
				acceptThread [i] = null;
				connectedThread [i] = null;
			}
		}
Пример #16
0
        public void Close()
        {
            try
            {
                _socket.Close();
                adapter.Dispose();

                _socket = null;
                adapter = null;
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.ToString());
                System.Diagnostics.Debugger.Break();
            }
        }
Пример #17
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;
            Android.Bluetooth.BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
            // is bluetooth enabled?

            // or
            bluetoothAdapter.Enable();
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Forms.Init(this, savedInstanceState);
            UserDialogs.Init(() => (Activity)Forms.Context);
            this.LoadApplication(new App());
        }
Пример #18
0
        public void ChangeBTStateTo(string state)
        {
            Android.Bluetooth.BluetoothAdapter bluetootAdapter = BluetoothAdapter.DefaultAdapter;

            if (state == "ON")
            {
                if (bluetootAdapter.IsEnabled == false)
                {
                    bluetootAdapter.Enable();
                }
            }
            else
            {
                if (bluetootAdapter.IsEnabled == true)
                {
                    bluetootAdapter.Disable();
                }
            }
        }
Пример #19
0
        public async Task <bool> BtConnect(string deviceAddress)
        {
            try
            {
                adapter = BluetoothAdapter.DefaultAdapter;
                if (adapter == null)
                {
                    throw new Exception("No Bluetooth adapter found.");
                }

                if (!adapter.IsEnabled)
                {
                    throw new Exception("Bluetooth adapter is not enabled.");
                }


                // Next, get an instance of the BluetoothDevice representing the physical device you’re connecting to.
                // You can get a list of currently paired devices using the adapter’s BondedDevices collection.
                // I use some simple LINQ to find the device I’m looking for:
                BluetoothDevice device = (from bd in adapter.BondedDevices
                                          //where bd.Name == "NameOfTheDevice"
                                          where bd.Address == deviceAddress
                                          select bd).FirstOrDefault();

                if (device == null)
                {
                    throw new Exception("Specified device not found.");
                }

                // Finally, use the device’s CreateRfCommSocketToServiceRecord method, which will return a BluetoothSocket
                // that can be used for connection and communication. Note that the UUID specified below is the standard UUID for SPP:
                _socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(Constants.BT_SERIAL_PORT_INTERFACE));
                await _socket.ConnectAsync().ConfigureAwait(false);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.ToString());
                System.Diagnostics.Debugger.Break();
            }

            return(IsOpen());
        }
Пример #20
0
		public Adapter ()
		{
			var appContext = Android.App.Application.Context;
			// get a reference to the bluetooth system service
			this._manager = (BluetoothManager) appContext.GetSystemService("bluetooth");
			this._adapter = this._manager.Adapter;

			this._gattCallback = new GattCallback (this);

			this._gattCallback.DeviceConnected += (object sender, DeviceConnectionEventArgs e) => {
				this._connectedDevices.Add ( e.Device);
				this.DeviceConnected (this, e);
			};

			this._gattCallback.DeviceDisconnected += (object sender, DeviceConnectionEventArgs e) => {
				// TODO: remove the disconnected device from the _connectedDevices list
				// i don't think this will actually work, because i'm created a new underlying device here.
				//if(this._connectedDevices.Contains(
				this.DeviceDisconnected (this, e);
			};
		}
Пример #21
0
        public async Task OpenBluetooth()
        {
            Android.Bluetooth.BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            // is bluetooth enabled?
            if (bluetoothAdapter.IsEnabled)
            {
                //  bluetoothAdapter.Disable();
            }
            else
            {
                bluetoothAdapter.Enable();

                MainActivity activity         = Forms.Context as MainActivity;
                var          permissionCheck  = ContextCompat.CheckSelfPermission(activity.BaseContext.ApplicationContext, Manifest.Permission.AccessCoarseLocation);
                var          permissionCheck1 = ContextCompat.CheckSelfPermission(activity.BaseContext.ApplicationContext, Manifest.Permission.AccessFineLocation);
            }


            // or
        }
Пример #22
0
        public BleServer(Context ctx)
        {
            _bluetoothManager = (BluetoothManager)ctx.GetSystemService(Context.BluetoothService);
            _bluetoothAdapter = _bluetoothManager.Adapter;

            _bluettothServerCallback = new BleGattServerCallback();
            _bluetoothServer = _bluetoothManager.OpenGattServer(ctx, _bluettothServerCallback);

            var service = new BluetoothGattService(UUID.FromString("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"),
                GattServiceType.Primary);
            _characteristic = new BluetoothGattCharacteristic(UUID.FromString("d8de624e-140f-4a22-8594-e2216b84a5f2"), GattProperty.Read | GattProperty.Notify | GattProperty.Write, GattPermission.Read | GattPermission.Write);
            _characteristic.AddDescriptor(new BluetoothGattDescriptor(UUID.FromString("28765900-7498-4bd4-aa9e-46c4a4fb7b07"),
                    GattDescriptorPermission.Read | GattDescriptorPermission.Write));

            service.AddCharacteristic(_characteristic);

            _bluetoothServer.AddService(service);

            _bluettothServerCallback.CharacteristicReadRequest += _bluettothServerCallback_CharacteristicReadRequest;
            _bluettothServerCallback.NotificationSent += _bluettothServerCallback_NotificationSent;

            Console.WriteLine("Server created!");

            BluetoothLeAdvertiser myBluetoothLeAdvertiser = _bluetoothAdapter.BluetoothLeAdvertiser;

            var builder = new AdvertiseSettings.Builder();
            builder.SetAdvertiseMode(AdvertiseMode.LowLatency);
            builder.SetConnectable(true);
            builder.SetTimeout(0);
            builder.SetTxPowerLevel(AdvertiseTx.PowerHigh);
            AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
            dataBuilder.SetIncludeDeviceName(true);
            //dataBuilder.AddServiceUuid(ParcelUuid.FromString("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"));
            dataBuilder.SetIncludeTxPowerLevel(true);

            myBluetoothLeAdvertiser.StartAdvertising(builder.Build(), dataBuilder.Build(), new BleAdvertiseCallback());
        }
Пример #23
0
        void findBTPrinter()
        {
            string printername = apara.PrinterName.Trim ().ToUpper ();
            //			string addrfile = getBTAddrFile(printername);
            //			if (tryConnectBtAddr(addrfile))
            //				return;

            try{
                mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                if (mBluetoothAdapter==null)
                {
                    Toast.MakeText (this, "Error initialize bluetooth Adapter. Try again", ToastLength.Long).Show ();
                    return;
                }
                string txt ="";
                if (!mBluetoothAdapter.Enable()) {
                    Intent enableBluetooth = new Intent(
                        BluetoothAdapter.ActionRequestEnable);
                    StartActivityForResult(enableBluetooth, 0);
                }

                var pair= mBluetoothAdapter.BondedDevices;
                if (pair.Count > 0) {
                    foreach (BluetoothDevice dev in pair) {
                        Console.WriteLine (dev.Name);
                        txt = txt+","+dev.Name;
                        if (dev.Name.ToUpper()==printername)
                        {
                            mmDevice = dev;
            //							File.WriteAllText(addrfile,dev.Address);
                            break;
                        }
                    }
                }
                Toast.MakeText (this, "found device " +mmDevice.Name, ToastLength.Long).Show ();
                //txtv.Text ="found device " +mmDevice.Name;
            }catch(Exception ex) {
                mmDevice = null;
                Toast.MakeText (this, "Error initialize bluetooth Adapter. Try again", ToastLength.Long).Show ();
            }
        }
Пример #24
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            if (D)
            {
                Log.E(TAG, "+++ ON CREATE +++");
            }

            // Set up the window layout
            SetContentView(R.Layout.main);

            // Get local Bluetooth adapter
            mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            // If the adapter is null, then Bluetooth is not supported
            if (mBluetoothAdapter == null)
            {
                Toast.MakeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).Show();
                Finish();
                return;
            }
        }
Пример #25
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			//Initialization
			// Get local Bluetooth adapter
			bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
			DeviceName = bluetoothAdapter.Name;
			handle = new MyHandler (this);

			messagesViewAdapter = new ArrayAdapter<string>(this, Resource.Layout.message);

			// If the adapter is null, then Bluetooth is not supported
			if (bluetoothAdapter == null) {
				Toast.MakeText (this, "Bluetooth is not available", ToastLength.Long).Show ();
				Finish ();
				return;
			}

			BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

			#region Home Screen UI stuff

			//set the content view to the home scree ui
			SetContentView (Resource.Layout.Home);

			//button handler for the only button - Math and Science Extravaganze with friends
			var butt = FindViewById<Button> (Resource.Id.gameButton);
			butt.Click += (object sender, EventArgs e) => {

				//build a dialog to ask for a new game or an exsiting game
				AlertDialog.Builder builder = new AlertDialog.Builder(this, 5);
				builder.SetTitle("Start Game?");
				builder.SetMessage("Do you want to start a new game or connect to an exsiting one?");

				//if new game launch the new game view which will get the number of players and the name of the device
				builder.SetPositiveButton("New Game", (s, ev) => {

					SetContentView(Resource.Layout.TextInput);

					var number = FindViewById<EditText>(Resource.Id.numPlayers);

					var name = FindViewById<EditText>(Resource.Id.editText1);


					var button = FindViewById<Button>(Resource.Id.createButton);

					button.Click += (object sender1, EventArgs e1) => {

						Console.WriteLine(number.Text.ToString());
						Console.WriteLine(name.Text.ToString());

						adapter.SetName(name.Text.ToString());

						maxDevices = Integer.ParseInt(number.Text.ToString());

						//enable discoverability for ever
						EnsureDiscoverable();

						dialogSpin = new ProgressDialog(this, 5);
						dialogSpin.SetProgressStyle(ProgressDialogStyle.Spinner);
						dialogSpin.SetMessage("Waiting for Other Devices");
						dialogSpin.Indeterminate = true;

						SetContentView(Resource.Layout.WaitView);

						dialogSpin.Show();
					};

				});

				//if exsiting game then start the device finding dialog and initiate a connection
				builder.SetNegativeButton("Existing Game", (s, ev) => {

					activeReturn = true;

					Intent serverIntent = new Intent(this, typeof(DeviceListActivity));

					StartActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
				});


				//show the dialog
				Dialog dialog = builder.Create();
				dialog.Show();
			};
			#endregion
				
		}
        //--------------------------------------------------------------
        // PRIVATE METHODS
        //--------------------------------------------------------------
        private void actualizeView()
        {
            // Get the local Bluetooth adapter
            _bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            // Get a set of currently paired devices
            ICollection<BluetoothDevice> pairedDevices = _bluetoothAdapter.BondedDevices;

            // If there are paired devices, add each one to the ArrayAdapter
            if(pairedDevices.Count > 0)
            {
                _pairedDevices.Clear();
                string name;
                foreach(BluetoothDevice device in pairedDevices)
                {
                    if(User.Instance.Friends.TryGetValue(device.Address, out name))
                    {
                        AddFriendDevice(device, name);
                    }
                    AddPairedDevice(device);
                }
            }
            else
            {
                AddPairedDevice(null);
            }

            if(_friendsDevices.Count == 0)
            {
                AddFriendDevice(null, Resources.GetString(Resource.String.none_friend));
            }
        }
Пример #27
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            adapter = BluetoothAdapter.DefaultAdapter;

            if (!adapter.IsEnabled) {

                Intent enableIntent = new Intent (BluetoothAdapter.ActionRequestEnable);
                StartActivityForResult (enableIntent, REQUEST_ENABLE_BT);

            }

            SetContentView (Resource.Layout.ConnectView);

            Intent discoverIntent = new Intent (BluetoothAdapter.ActionRequestDiscoverable);
            discoverIntent.PutExtra (BluetoothAdapter.ExtraDiscoverableDuration, 0);
            StartActivity (discoverIntent);

            DoDiscovery ();

            this.pairedDevicesAA = new ArrayAdapter<string>(this, Resource.Layout.BluetoothTextView);
            newDevicesAA = new ArrayAdapter<string>(this, Resource.Layout.BluetoothTextView);

            var pairedListView = FindViewById<ListView> (Resource.Id.PairedListView);
            pairedListView.Adapter = this.pairedDevicesAA;
            pairedListView.ItemClick += DeviceListClick;

            var newListView = FindViewById<ListView> (Resource.Id.NewListView);
            newListView.Adapter = newDevicesAA;
            newListView.ItemClick += DeviceListClick;

            var refreshButton = FindViewById<Button> (Resource.Id.refresh);
            refreshButton.Click += (object sender, EventArgs e) => {

                newDevicesAA.Clear();

                DoDiscovery();
            };

            var doneButton = FindViewById<Button> (Resource.Id.DoneButton);
            doneButton.Click += (object sender, EventArgs e) => {

                Finish();
            };

            receiver = new Receiver (this);
            var filter = new IntentFilter (BluetoothDevice.ActionFound);
            RegisterReceiver (receiver, filter);

            // Register for broadcasts when discovery has finished
            filter = new IntentFilter (BluetoothAdapter.ActionDiscoveryFinished);
            RegisterReceiver (receiver, filter);

            var pairedDevices = adapter.BondedDevices;

            // If there are paired devices, add each one to the ArrayAdapter
            if (pairedDevices.Count > 0) {
                FindViewById<View> (Resource.Id.title).Visibility = ViewStates.Visible;
                foreach (var device in pairedDevices) {
                    this.pairedDevicesAA.Add (device.Name + "\n" + device.Address);
                }
            } else {
                String noDevices = Resources.GetText (Resource.String.none_paired);
                this.pairedDevicesAA.Add (noDevices);
            }
        }
Пример #28
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			
			if (Debug)
				Log.Error (TAG, "+++ ON CREATE +++");
			
			// Set up the window layout
			RequestWindowFeature (WindowFeatures.CustomTitle);
			SetContentView (Resource.Layout.main);
			Window.SetFeatureInt (WindowFeatures.CustomTitle, Resource.Layout.custom_title);
	
			// Set up the custom title
			title = FindViewById<TextView> (Resource.Id.title_left_text);
			title.SetText (Resource.String.app_name);
			title = FindViewById<TextView> (Resource.Id.title_right_text);
	
			// Get local Bluetooth adapter
			bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
	
			// If the adapter is null, then Bluetooth is not supported
			if (bluetoothAdapter == null) {
				Toast.MakeText (this, "Bluetooth is not available", ToastLength.Long).Show ();
				Finish ();
				return;
			}
		}
		/**
     	* Initializes a reference to the local Bluetooth adapter.
     	*
     	* @return Return true if the initialization is successful.
    	 */
		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) {
					Log.Error (TAG, "Unable to initialize BluetoothManager.");
					return false;
				}
			}

			mBluetoothAdapter = mBluetoothManager.Adapter;
			if (mBluetoothAdapter == null) {
				Log.Error (TAG, "Unable to obtain a BluetoothAdapter.");
				return false;
			}

			return true;
		}
Пример #30
0
        private void findBTPrinter()
        {
            btdevices.Clear ();
             try{
                mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                if (mBluetoothAdapter==null)
                {
                    Toast.MakeText (this, "Error initialize bluetooth Adapter. Try again", ToastLength.Long).Show ();
                    return;
                }
                if (!mBluetoothAdapter.Enable()) {
                    Intent enableBluetooth = new Intent(
                        BluetoothAdapter.ActionRequestEnable);
                    StartActivityForResult(enableBluetooth, 0);
                }

                var pair= mBluetoothAdapter.BondedDevices;
                if (pair.Count > 0) {
                    foreach (BluetoothDevice dev in pair) {
                        btdevices.Add(dev.Name);
                    }
                }

                adapterBT = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, btdevices.ToArray());
                adapterBT.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
                spinBt.Adapter = adapterBT;
                spinBt.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> ( SpinBt_ItemClick );
                //txtv.Text ="found device " +mmDevice.Name;
            }catch(Exception ex) {

                Toast.MakeText (this, "Error initialize bluetooth Adapter. Try again", ToastLength.Long).Show ();
            }
        }
Пример #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BluetoothHub"/> class.
 /// </summary>
 /// <param name="adapter">The adapter.</param>
 public BluetoothHub(BluetoothAdapter adapter)
 {
     _adapter = adapter;
 }
		public const int STATE_CONNECTED = 3;  // now connected to a remote device
		
		/// <summary>
		/// Constructor. Prepares a new BluetoothChat session.
		/// </summary>
		/// <param name='context'>
		/// The UI Activity Context.
		/// </param>
		/// <param name='handler'>
		/// A Handler to send messages back to the UI Activity.
		/// </param>
		public BluetoothChatService (Context context, Handler handler)
		{
			_adapter = BluetoothAdapter.DefaultAdapter;
			_state = STATE_NONE;
			_handler = handler;
		}
Пример #33
0
		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Setup the window
			RequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
			SetContentView(R.Layout.device_list);

			// Set result CANCELED in case the user backs out
			SetResult(Activity.RESULT_CANCELED);

			// Initialize the button to perform device discovery
			var scanButton = (Button) FindViewById(R.Id.button_scan);
		    scanButton.Click += (s, x) => {
		        doDiscovery();
                ((View)s).SetVisibility(View.GONE);
		    };

			// Initialize array adapters. One for already paired devices and
			// one for newly discovered devices
			mPairedDevicesArrayAdapter = new ArrayAdapter<string>(this, R.Layout.device_name);
			mNewDevicesArrayAdapter = new ArrayAdapter<string>(this, R.Layout.device_name);

			// Find and set up the ListView for paired devices
			var pairedListView = (ListView) FindViewById(R.Id.paired_devices);
			pairedListView.Adapter = mPairedDevicesArrayAdapter;
		    pairedListView.ItemClick += OnDeviceClick;

			// Find and set up the ListView for newly discovered devices
			ListView newDevicesListView = (ListView) FindViewById(R.Id.new_devices);
			newDevicesListView.Adapter = mNewDevicesArrayAdapter;
			newDevicesListView.ItemClick += OnDeviceClick;

			// Register for broadcasts when a device is discovered
			IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
			this.RegisterReceiver(mReceiver, filter);

			// Register for broadcasts when discovery has finished
			filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
			this.RegisterReceiver(mReceiver, filter);

			// Get the local Bluetooth adapter
			mBtAdapter = BluetoothAdapter.GetDefaultAdapter();

			// Get a set of currently paired devices
			var pairedDevices = mBtAdapter.BondedDevices;

			// If there are paired devices, add each one to the ArrayAdapter
			if (pairedDevices.Size() > 0)
			{
				FindViewById(R.Id.title_paired_devices).Visibility = View.VISIBLE;
				foreach (BluetoothDevice device in pairedDevices.AsEnumerable())
				{
					mPairedDevicesArrayAdapter.Add(device.Name + "\n" + device.Address);
				}
			}
			else
			{
				string noDevices = Resources.GetText(R.String.none_paired).ToString();
				mPairedDevicesArrayAdapter.Add(noDevices);
			}
		}
		public const int STATE_CONNECTED = 3; // now connected to a remote device

		/// <summary>
		/// Constructor. Prepares a new BluetoothChat session. </summary>
		/// <param name="context">  The UI Activity Context </param>
		/// <param name="handler">  A Handler to send messages back to the UI Activity </param>
		public BluetoothChatService(Context context, Handler handler)
		{
			mAdapter = BluetoothAdapter.GetDefaultAdapter();
			mState = STATE_NONE;
			mHandler = handler;
		}
Пример #35
0
        bool tryConnectBtAddr(string btAddrfile)
        {
            bool found = false;
            if (!File.Exists (btAddrfile))
                return false;
            try{
            mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
            mmDevice = mBluetoothAdapter.GetRemoteDevice (File.ReadAllBytes (btAddrfile));
            if (mmDevice != null) {
                found = true;
            }

            }catch(Exception ex) {

            }
            return found;
        }
Пример #36
0
        public async Task<bool> Init(bool simulatormode = false)
        {
            running = true;
            //initialize _data
            data = new Dictionary<string, string> {{"vin", DefValue}};
            //VIN
            piDs = ObdShare.ObdUtil.GetPIDs();
            foreach (var v in piDs.Values)
            {
                data.Add(v, DefValue);
            }

            this.simulatormode = simulatormode;
            if (simulatormode)
            {
                return true;
            }

            bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
            if (bluetoothAdapter == null)
            {
                System.Diagnostics.Debug.WriteLine("Bluetooth is not available");
                return false;
            }
            try
            {
                var ba = bluetoothAdapter.BondedDevices;
                foreach (var bd in ba)
                {
                    if (bd.Name.ToLower().Contains("obd"))
                        bluetoothDevice = bd;
                }
                if (bluetoothDevice == null)
                {
                    return false;
                }
                bluetoothSocket = bluetoothDevice.CreateRfcommSocketToServiceRecord(SppUuid);

                await bluetoothSocket.ConnectAsync();
                connected = true;
            }
            catch (Java.IO.IOException)
            {
                // Close the socket
                try
                {
                    connected = false;
                    bluetoothSocket.Close();
                }
                catch (Java.IO.IOException)
                {
                }
                catch (Exception)
                {
                }

                return false;
            }
            catch (Exception)
            {
            }
            if (connected)
            {
                reader = bluetoothSocket.InputStream;
                writer = bluetoothSocket.OutputStream;

                string s;
                s = await SendAndReceive("ATZ\r");
                s = await SendAndReceive("ATE0\r");
                s = await SendAndReceive("ATL1\r");
                s = await SendAndReceive("ATSP00\r");
                
                PollObd();
                
                return true;
            }
            else
                return false;
        }
Пример #37
0
        public BluetoothAdapter(Context context)
        {
            Context = context;

            _bluetoothAdapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;
        }