I was working on a android project that requires printing from a device using a bluetooth printer, After searching for tutorials and links on how to accomplish this, i was able to find something slightly useful here
I tweaked the code a little bit and it’s explained below
First Create a new Project ( I am using Android Studio, but you can go ahead and use Eclipse or any other IDE of your choice)
File -> New -> Project -> BluetoothPrintingExample
Select Empty Activity as default activity template
inside activity_main.xml copy and paste the following
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.bluetooth.MainActivity">
<Button
android:id="@+id/BtnPrint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Print"></Button>
</LinearLayout>
Go into your MainActivity.java, inside onCreate copy and paste the following
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainBtn = (Button)findViewById(R.id.BtnPrint);
mainBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentPrint("\nThis is me testing this app\n Hello World, it's John Oke\n Testing Bluetooth Printing\n");
}
});
Also add the following import statements before your class definition
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
Before onCreate, copy and paste the following
Button mainBtn;
BluetoothAdapter bluetoothAdapter;
BluetoothSocket socket;
BluetoothDevice bluetoothDevice;
OutputStream outputStream;
InputStream inputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
String value = "";
Create a new method, call it InitPrinter() and paste the following inside the method body
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try
{
if(!bluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("SP200")) //Note, you will need to change this to match the name of your device
{
bluetoothDevice = device;
break;
}
}
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
Method m = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket) m.invoke(bluetoothDevice, 1);
bluetoothAdapter.cancelDiscovery();
socket.connect();
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
beginListenForData();
}
else
{
value+="No Devices found";
Toast.makeText(this, value, Toast.LENGTH_LONG).show();
return;
}
}
catch(Exception ex)
{
value+=ex.toString()+ "\n" +" InitPrinter \n";
Toast.makeText(this, value, Toast.LENGTH_LONG).show();
}
Create another method beginListenForData() and paste the following inside the method body
try {
final Handler handler = new Handler();
// this is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = inputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
inputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(
readBuffer, 0,
encodedBytes, 0,
encodedBytes.length
);
// specify US-ASCII encoding
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
// tell the user data were sent to bluetooth printer device
handler.post(new Runnable() {
public void run() {
Log.d("e", data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
Also create a method IntentPrint (Note this method was called in onCreate above)that takes a string parameter txtvalue and paste the following
byte[] buffer = txtvalue.getBytes();
byte[] PrintHeader = { (byte) 0xAA, 0x55,2,0 };
PrintHeader[3]=(byte) buffer.length;
InitPrinter();
if(PrintHeader.length>128)
{
value+="\nValue is more than 128 size\n";
Toast.makeText(this, value, Toast.LENGTH_LONG).show();
}
else
{
try
{
outputStream.write(txtvalue.getBytes());
outputStream.close();
socket.close();
}
catch(Exception ex)
{
value+=ex.toString()+ "\n" +"Excep IntentPrint \n";
Toast.makeText(this, value, Toast.LENGTH_LONG).show();
}
}
Finally inside your AndroidManifest, add the following permissions
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
Connect your Android Device, Put on your Bluetooth printer, and pair your device(phone, tablet etc) with the printer. Don’t forget to replace “SP200” in above with your Printer’s Name. Now run your application and click on the Print button. You have successfully created an application that prints via bluetooth
The Full code can be found on github see link below