Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DiomedesDominguez/70d7370d1190b3fbb36dce60a62e6cd6 to your computer and use it in GitHub Desktop.
Save DiomedesDominguez/70d7370d1190b3fbb36dce60a62e6cd6 to your computer and use it in GitHub Desktop.
Code Snippet for a Bluetooth mobile printing service
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice mmDevice = null;
private BluetoothSocket mmSocket = null;
private Stream mmOutputStream;
private Stream mmInputStream;
private void FindPrinter()
{
try
{
mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
if (mBluetoothAdapter == null)
{
UserDialogs.Instance.Alert(Recursos.MissingBluetoothAdapter, Recursos.ErrorTitle, Recursos.NeutralButton);
return;
}
if (!mBluetoothAdapter.IsEnabled)
{
Intent enableBluetooth = new Intent
(BluetoothAdapter.ActionRequestEnable);
StartActivityForResult(enableBluetooth, 0);
}
ICollection<BluetoothDevice> pairedDevices = mBluetoothAdapter.BondedDevices;
if (pairedDevices.Count > 0)
{
foreach (BluetoothDevice device in pairedDevices)
{
if (device.Name == Recursos.BluetoothDevice)
{
mmDevice = device;
break;
}
}
}
if (mmDevice == null)
{
UserDialogs.Instance.Alert(string.Format(Recursos.MissingBluetoothDevice, Recursos.BluetoothDevice), Recursos.ErrorTitle, Recursos.NeutralButton);
}
}
catch (Exception ex)
{
UserDialogs.Instance.Alert(ex.Message, Recursos.ErrorTitle, Recursos.NeutralButton);
}
}
// Tries to open a connection to the bluetooth printer device
private void OpenPrinter()
{
try
{
if(mmDevice == null)
return;
// Standard SerialPortService ID
UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
mmSocket = mmDevice.CreateInsecureRfcommSocketToServiceRecord(uuid);
mmSocket.Connect();
mmOutputStream = mmSocket.OutputStream;
mmInputStream = mmSocket.InputStream;
beginListenForData();
}
catch (Exception ex)
{
//myLabel.Text = ex.ToString ();
}
}
// After opening a connection to bluetooth printer device,
// we have to listen and check if a data were sent to be printed.
private void beginListenForData()
{
}
public void sendData()
{
try
{
OpenPrinter();
if (mmOutputStream == null)
{
return;
}
// the text typed by the user
var msg = "Hello world";
msg += "\n";
byte[] dBytes = System.Text.Encoding.GetEncoding(1252).GetBytes(msg);
mmOutputStream.Write(dBytes, 0, dBytes.Length);
}
catch (Exception ex)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment