//Evento de conexion al Bluetooth public void Connect() { //asignamos el sensor bluetooth con el que vamos a trabajar mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; //Verificamos que este habilitado if (!mBluetoothAdapter.Enable()) { Toast.MakeText(this, "Bluetooth Desactivado", ToastLength.Short).Show(); } //verificamos que no sea nulo el sensor if (mBluetoothAdapter == null) { Toast.MakeText(this, "Bluetooth No Existe o esta Ocupado", ToastLength.Short) .Show(); } //Iniciamos la conexion con el arduino BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address); System.Console.WriteLine("Conexion en curso" + device); //Indicamos al adaptador que ya no sea visible mBluetoothAdapter.CancelDiscovery(); try { //Inicamos el socket de comunicacion con el arduino btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID); //Conectamos el socket btSocket.Connect(); System.Console.WriteLine("Conexion Correcta"); } catch (System.Exception e) { //en caso de generarnos error cerramos el socket Console.WriteLine(e.Message); try { btSocket.Close(); } catch (System.Exception) { System.Console.WriteLine("Imposible Conectar"); } System.Console.WriteLine("Socket Creado"); } //Una vez conectados al bluetooth mandamos llamar el metodo que generara el hilo //que recibira los datos del arduino beginListenForData(); //NOTA envio la letra e ya que el sketch esta configurado para funcionar cuando //recibe esta letra. //dataToSend = new Java.Lang.String("Hola"); //writeData(dataToSend); }
private void FindBTPrinter() { string printername = apara.PrinterName.Trim ().ToUpper (); try{ mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; if (mBluetoothAdapter ==null) { msg = callingActivity.Resources.GetString(Resource.String.msg_bluetoothnofound); 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; } } } msg= callingActivity.Resources.GetString(Resource.String.msg_bluetoothfound) +mmDevice.Name; }catch { //txtv.Text = ex.Message; mmDevice = null; msg = callingActivity.Resources.GetString(Resource.String.msg_bluetoothnofound); //AlertShow(ex.Message); }finally { if (mBluetoothAdapter != null) { if (mBluetoothAdapter.IsDiscovering) { mBluetoothAdapter.CancelDiscovery (); Thread.Sleep (300); } mBluetoothAdapter.Dispose (); mBluetoothAdapter = null; } } }