Android Bluetooth Printing Example Code with Actual Printer Device
Recently, I was asked to make a program for printing some data to a small or handheld Bluetooth printer device.
This can be used for printing receipts, simple tickets, or customer notes.
I like how it works because usually, we are getting our program output on a computer screen.
But this time we are getting our output on a tangible paper!
This code will simply let you connect to the Bluetooth printer, type a text that you want to be printed and click the “send” button to print.
As for the printing with images, we made another code for that, please see section 4.3 (April 15, 2015 update) below!
1.0 Bluetooth Printing Source Codes
Step 1: Put the following code on your MainActivity.java. These imports are needed to perform our Android printing operations via Bluetooth.
import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.TextView; import android.widget.EditText; import android.widget.Button; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import java.util.UUID; public class MainActivity extends Activity { }
Step 2: Inside your MainActivity class will be the following variable declarations.
// will show the statuses like bluetooth open, close or data sent TextView myLabel; // will enable user to enter any text to be printed EditText myTextbox; // android built in classes for bluetooth operations BluetoothAdapter mBluetoothAdapter; BluetoothSocket mmSocket; BluetoothDevice mmDevice; // needed for communication to bluetooth device / network OutputStream mmOutputStream; InputStream mmInputStream; Thread workerThread; byte[] readBuffer; int readBufferPosition; volatile boolean stopWorker;
Step 3: After the variable codes, we will have the following onCreate() method.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // more codes will be here }catch(Exception e) { e.printStackTrace(); } }
Step 4: Our XML layout file called activity_main.xml located in res/layout/ directory will have the following codes.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="10dp"> <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:" /> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/label" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/entry"> <Button android:id="@+id/open" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:text="Open" /> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" /> <Button android:id="@+id/close" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Close" /> </LinearLayout> </RelativeLayout>
Step 5: Inside the try-catch of your onCreate() method we will define the TextView label, EditText input box and buttons based on our XML layout file in Step 4.
// we are going to have three buttons for specific functions Button openButton = (Button) findViewById(R.id.open); Button sendButton = (Button) findViewById(R.id.send); Button closeButton = (Button) findViewById(R.id.close); // text label and input box myLabel = (TextView) findViewById(R.id.label); myTextbox = (EditText) findViewById(R.id.entry);
Step 6: We will set the onClickListener of our open button. This will open the connection between the android device and Bluetooth printer.
// open bluetooth connection openButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { findBT(); openBT(); } catch (IOException ex) { ex.printStackTrace(); } } });
Step 7: findBT() method will try to find available Bluetooth printer. It will not work without the following code. Put it below the onCreate() method.
// this will find a bluetooth printer device void findBT() { try { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter == null) { myLabel.setText("No bluetooth adapter available"); } if(!mBluetoothAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, 0); } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if(pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { // RPP300 is the name of the bluetooth printer device // we got this name from the list of paired devices if (device.getName().equals("RPP300")) { mmDevice = device; break; } } } myLabel.setText("Bluetooth device found."); }catch(Exception e){ e.printStackTrace(); } }
Step 8: openBT() method will open the connection to Bluetooth printer found during the findBT() method. It will not work without the following code. Put it below the findBT() method.
// tries to open a connection to the bluetooth printer device void openBT() throws IOException { try { // Standard SerialPortService ID UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); mmSocket.connect(); mmOutputStream = mmSocket.getOutputStream(); mmInputStream = mmSocket.getInputStream(); beginListenForData(); myLabel.setText("Bluetooth Opened"); } catch (Exception e) { e.printStackTrace(); } }
Step 9: We need beginListenForData() method so that openBT() method will work.
/* * after opening a connection to bluetooth printer device, * we have to listen and check if a data were sent to be printed. */ void beginListenForData() { 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 = mmInputStream.available(); if (bytesAvailable > 0) { byte[] packetBytes = new byte[bytesAvailable]; mmInputStream.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() { myLabel.setText(data); } }); } else { readBuffer[readBufferPosition++] = b; } } } } catch (IOException ex) { stopWorker = true; } } } }); workerThread.start(); } catch (Exception e) { e.printStackTrace(); } }
Step 10: We will make an onClickListener for the “Send” button. Put the following code after the onClickListener of the “Open” button, inside onCreate() method.
// send data typed by the user to be printed sendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { sendData(); } catch (IOException ex) { ex.printStackTrace(); } } });
Step 11: sendData() method is needed so that the “Open” button will work. Put it below the beginListenForData() method code block.
// this will send text data to be printed by the bluetooth printer void sendData() throws IOException { try { // the text typed by the user String msg = myTextbox.getText().toString(); msg += "\n"; mmOutputStream.write(msg.getBytes()); // tell the user data were sent myLabel.setText("Data sent."); } catch (Exception e) { e.printStackTrace(); } }
Step 12: We will code an onClickListener for the “close” button so we can close the connection to Bluetooth printer and save battery. Put the following code after the onClickListener of the “Send” button, inside onCreate() method.
// close bluetooth connection closeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { closeBT(); } catch (IOException ex) { ex.printStackTrace(); } } });
Step 13: closeBT() method in Step 12 will not work without the following code. Put it below the sendData() method code block.
// close the connection to bluetooth printer. void closeBT() throws IOException { try { stopWorker = true; mmOutputStream.close(); mmInputStream.close(); mmSocket.close(); myLabel.setText("Bluetooth Closed"); } catch (Exception e) { e.printStackTrace(); } }
Step 14: Make sure the BLUETOOTH permission was added to your manifest file. It is located in manifests/AndroidManifest.xml, the code inside should look like the following.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.bluetoothprinter" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <supports-screens android:anyDensity="true" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
2.0 LEVEL 1 Source Code Output
Step 1: Click the “Open” button, the “Type here” text will change to “Bluetooth Opened”
Step 2: Type any text in the text box or EditText.
Step 3: Click the “Send” button, Bluetooth Printer device will print the text you typed in Step 2.
Step 4: Click the “Close” button to close Bluetooth connection and save battery.
Need to buy the same printer model we used above? I will give you the contact information of our supplier. Send an email to mike@codeofaninja.com with a subject “Bluetooth printer by codeofaninja.com”. I will reply with the contact information of our supplier.
3.0 LEVEL 2 Source Code Output
The LEVEL 2 source code can print small images. As you will see in the video, you can browse the image and then the Bluetooth printer will print it.
Need to buy the same printer model we used above? I will give you the contact information of our supplier. Send an email to mike@codeofaninja.com with a subject “Bluetooth printer by codeofaninja.com”. I will reply with the contact information of our supplier.
Please note that you have to pair your Android device (in your Bluetooth settings) and Bluetooth printer before running our source code.
4.0 Download Source Code
4.1 Downloading The Source Code
You can get the source code by following the source code above. But isn’t it more convenient if you can just download the complete source code we used, import it and play around it?
There’s a small fee in getting the complete source code, it is small compared to the value, skill upgrade, and career upgrade it can bring you, or income you can get from your android app project or business.
Download the source code by clicking the “Buy Now” button below. What will you get? The source codes and free code updates!
4.2 LEVEL 1 Source Code
LEVEL 1 is the complete source code of our tutorial above.
4.3 LEVEL 2 Source Code
Here’s the source code version where you can print images (see output video demo on section 3.0 above). The source code can let you browse an image and then print it in the Bluetooth printer.
Images must be small and less than 10KB in size only, anything more than that, the printing will fail.
4.4 Download ALL LEVELS Source Code
This means you will download LEVEL 1 and LEVEL 2 source codes above at a discounted price.
IMPORTANT NOTE: This code was only tested with the printer we specified above. It may not work with your kind of printer. We provide the code as is. Download it at your own risk.
Also, thanks to a code from project green giant for helping me figure out this Android Bluetooth printing code example.