Android Bluetooth Printing Example Code with Actual Printer Device

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.

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.

212 replies
    • Mike Dalisay
      Mike Dalisay says:

      Hi @384f8d64c77e5048c202661b78d018ae:disqus , I think that’s just a worker thread waiting to be interrupted by the user (when he click the send button). It analyzes the structure of the data to be printed by bytes and check for delimeter, etc… Anyone out there got better explanation? :)

      Reply
    • Mike Dalisay
      Mike Dalisay says:

      Hi @e05d760241935e822cad6d2c163e0029:disqus, did you make sure your bluetooth device is connected? See this part of the code…

      if (device.getName().equals(“MP300”)) {…

      MP300 might not be the name of your bluetooth device…

      Reply
  1. Joey Graziano
    Joey Graziano says:

    Is anyone else getting an error in the MainActivity.java file?
    I am using eclipse and simply just imported this file into my IDE. I would love to play around with this application

    Reply
  2. Sapna
    Sapna says:

    I am Trying to print a Receipt after every transaction (payment in my case). But i am facing a problem when i give print one after the other i.e.; when i give a print for more than two times my App is getting Struck

    Reply
  3. Sumit Kumar
    Sumit Kumar says:

    hi
    I m Trying to build Chat app. in my website with Login only unique id ans also store every chat history in my database;i can’t understand how to do please give me some guideline.

    sumit kumar(sumitkasaudhan1@gmail.com)

    Reply
      • ahmed ali
        ahmed ali says:

        Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible

        Reply
          • ahmed ali
            ahmed ali says:

            Sir you are saying right but i want to simply send data from one device to another .sir kindly give me the code and thanks in advance

          • ahmed ali
            ahmed ali says:

            SIr i try this code before basically major problem in this code is “uuid” is not present .SIr tell me what changes is reqiured in your project ” Bluetooth send data to Bluetooth printer “. My goal is to send file from one andriod phone toanother andriod phone through bluetooth .I know you will solve my problem as soon as possible sir i am waiting for your reply .

          • ahmed ali
            ahmed ali says:

            sir i try this code before but this is not working .S ir what changes is required in your code ” Android Bluetooth Code to Print Text on a Bluetooth Printer “.
            My goal is to send file from one andriod phone to another andriod phone .Sir i know you solve my problem plz sir reply me as soon as possible.thanks

          • ahmed ali
            ahmed ali says:

            Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible

          • ahmed ali
            ahmed ali says:

            Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible

          • ahmed ali
            ahmed ali says:

            Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible

          • ahmed ali
            ahmed ali says:

            Sir want change is reqiured in your code” bluetooth send data to bluetooth printer ” My goal is to send file from one andriod phone to another andriod phone i know you solve my problem as soon as possible.

  4. Louie Batad Policarpio
    Louie Batad Policarpio says:

    Hi!!! iIm having a problem in some device, it is working fine in Sony xperia and samsung galaxy, but not in Myphone and acer tablet. it doest’n connect to the printer..

    Reply
  5. Ing. Williams Aguilera
    Ing. Williams Aguilera says:

    Hi! I have an Intermac printer, and it doesn’t accept pairing, is there a way to send the printer data, without pairing (bonding) the device, I’m trying to do it, but it promts me a message to enter the pin, and when I fail to do that it throws an exception

    Reply
  6. Kadir Leblebici
    Kadir Leblebici says:

    Hi,

    a very nice example of working
    Russian characters unit does not print properly (Windows-1251 encoding of the printer)

    What can we do about it?
    Printer model=Sewoo lk-p30

    Thanks

    Reply
  7. SantiMe
    SantiMe says:

    AWESOME JOB!:. THank you so much.. it helped me a lot.. the only problem I had.. was that this permission was missing in the in the manifest, without it I counldn’t print.

    But everything else works fine :D

    Reply
  8. Set
    Set says:

    Hy! I have a problem, on this string mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

    And not performed on. Pleas help!

    Reply
  9. TA'Kiz Wanarin
    TA'Kiz Wanarin says:

    Hi! i’m having a problem in some device, My’s device Samsung galaxy note 2 and printer epson lq300 [have bluetooth printer adapter act bt5800 ub]
    please help

    Reply
    • ninjazhai
      ninjazhai says:

      Hi @takizwanarin:disqus, what exactly is the problem you’re facing, can you tell us some error messages? We don’t have your devices to test it out. Thanks! :D

      Reply
    • Murugan
      Murugan says:

      Yes sir..i think my (MPD2 bluetooth printer)printer does not support for tamilcharacters… which printer will support tamil font pls tell me sir…

      Reply
  10. Osman Razak
    Osman Razak says:

    I am using samsung galaxy pocket with Blue Bamboo printer but it does not send any command to the Printer it only write Bluetooth Device found. Please help me out .

    Reply
    • ninjazhai
      ninjazhai says:

      Sorry for the late reply @juanjosemirc:disqus, I think what you need now is a large printer device and not like the example above where you print on a small and handheld printer device. I have no experience printing a pdf file in this case.

      Reply
      • Juan Jose Mir C
        Juan Jose Mir C says:

        OK, i see, but forget the pdf file. How can i print a picture, a litte picture like a logo. is it possible? your android code is very good for text, but i want print a picture or a file, please help me, thanks!

        Reply
  11. ninjazhai
    ninjazhai says:

    @juanjosemirc:disqus and others who require printing an image or pdf files, I added an important note above stating that the code can print only texts. Some good people might want to contribute to this post and add that functionality.

    Right now, I don’t have enough time to research about it, but if I have, I’ll surely update this post and notify you via email (if you’re subscribed), thanks for understanding!

    Reply
  12. Mainak
    Mainak says:

    Which printer do you use(printer company name and also model number)? Because I am new in android. please help me. Also this printer is available in India ?

    I can not download your source code. please send me download file if it is possible.

    Reply
  13. Mainak
    Mainak says:

    please tell me which printer( company name & model no.) did you used in this program.
    I am new in android, please help me.

    Reply
  14. Shashiraj
    Shashiraj says:

    Hi, I am trying to print an invoice using a bluetooth printer. There is no issue with the printing. The issue is the data formatting before printing. The data gets shattered in the receipt. I used Outputstream to print and passed string to that.Please do reply if there is any solution to format the data before printing.

    Reply
    • Louie Batad Policarpio
      Louie Batad Policarpio says:

      Its depend on your printer, Sample shown below are apex3 printer code….

      public class PrinterCommands {

      public static byte[] INIT = {27, 64};
      public static byte[] RESET = {24};
      public static final byte[] AUTO_POWER_OFF = {27,77,55,54,53,52,48,13};
      public static byte[] SELECT_FONT_A = {27, 33, 0};
      public static byte[] SELECT_FONT_12 = {27, 75, 49, 13};
      public static byte[] SELECT_FONT_25 = {27, 75, 49, 49, 13};
      public static byte[] FONT_BOLD_ON = {27, 85, 49};
      public static byte[] FONT_BOLD_OFF = {27, 85, 48};
      public static byte[] FONT_UNDERLINE_ON = {27, 85, 85};
      public static byte[] FONT_UNDERLINE_OFF = {27, 85, 117};
      public static byte[] FONT_HI_ON = {28};
      public static byte[] FONT_HI_OFF = {29};
      public static byte[] FONT_WIDE_ON = {14};
      public static byte[] FONT_WIDE_OFF = {15};
      public static byte[] CHAR_SET = {27, 70, 49};
      public static byte[] PRINT_LEFT = {27, 70, 76};
      public static byte[] PRINT_RIGHT = {27, 70, 86};
      public static byte[] SET_BAR_CODE_HEIGHT = {29, 104, 100};
      public static byte[] PRINT_BAR_CODE_1 = {29, 107, 2};
      public static byte[] SEND_NULL_BYTE = {0x00};
      public static byte[] SELECT_PRINT_SHEET = {0x1B, 0x63, 0x30, 0x02};
      public static byte[] FEED_PAPER_AND_CUT = {0x1D, 0x56, 66, 0x00};
      public static byte[] SELECT_CYRILLIC_CHARACTER_CODE_TABLE = {0x1B, 0x74, 0x11};

      }

      and sample below how to use it

      mmOutputStream.write(PrinterCommands.INIT);
      mmOutputStream.write(PrinterCommands.SELECT_FONT_25);
      mmOutputStream.write(PrinterCommands.FONT_HI_ON);
      mmOutputStream.write(PrinterCommands.RESET);

      Reply
    • Guest
      Guest says:

      Its depend on your printer, Sample shown below are apex3 printer code….

      and sample below how to use it

      mmOutputStream.write(PrinterCommands.INIT);
      mmOutputStream.write(PrinterCommands.SELECT_FONT_25);
      mmOutputStream.write(PrinterCommands.FONT_HI_ON);
      mmOutputStream.write(PrinterCommands.RESET);

      Reply
  15. Ricardo Lahosa Laguna
    Ricardo Lahosa Laguna says:

    Hello, can you help me?
    I need to print to the printer ─ characters chr (196) chr ┼ (197) ├ chr (195), ┬ chr (194), etc..
    I can not print these characters.

    Reply
  16. JOHN njoroge
    JOHN njoroge says:

    Great tutorial. it’s a great help.
    my problem is with the statement
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); -MainActivity.java:156)
    mmSocket.connect();
    my log:-
    07-18 16:48:23.639: W/System.err(12643): java.lang.NullPointerException
    07-18 16:48:23.669: W/System.err(12643): at com.example.bluetoothprinter.MainActivity.openBT(MainActivity.java:156)
    07-18 16:48:23.669: W/System.err(12643): at com.example.bluetoothprinter.MainActivity$1.onClick(MainActivity.java:64)
    07-18 16:48:23.669: W/System.err(12643): at android.view.View.performClick(View.java:3660)
    07-18 16:48:23.669: W/System.err(12643): at android.view.View$PerformClick.run(View.java:14427)
    07-18 16:48:23.669: W/System.err(12643): at android.os.Handler.handleCallback(Handler.java:605)
    07-18 16:48:23.669: W/System.err(12643): at android.os.Handler.dispatchMessage(Handler.java:92)
    07-18 16:48:23.669: W/System.err(12643): at android.os.Looper.loop(Looper.java:137)
    07-18 16:48:23.669: W/System.err(12643): at android.app.ActivityThread.main(ActivityThread.java:4517)
    07-18 16:48:23.669: W/System.err(12643): at java.lang.reflect.Method.invokeNative(Native Method)
    07-18 16:48:23.669: W/System.err(12643): at java.lang.reflect.Method.invoke(Method.java:511)
    07-18 16:48:23.669: W/System.err(12643): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:995)
    07-18 16:48:23.669: W/System.err(12643): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
    07-18 16:48:23.669: W/System.err(12643): at dalvik.system.NativeStart.main(Native Method)

    Reply
    • ninjazhai
      ninjazhai says:

      Hey @disqus_nYnzGXSTKm:disqus , thanks for the report, but does your app crashes? Or it just show these logs? If it works correctly, you can just catch these logs.

      Reply
    • SgtBurned
      SgtBurned says:

      java.lang.NullPointerException

      Suggests that you haven’t setup the uuid. So there isn’t a socket connected and it returns null.

      Reply
  17. Manivannan C
    Manivannan C says:

    Hi,

    The coding works perfectly, but i want to print all items from listview if number of columns and rows are available.

    So please tell me how to print this. if you have any sample like this please give me

    Reply
    • ninjazhai
      ninjazhai says:

      Hello @moiky:disqus, you’re welcome! However, I don’t know how to do that too, I haven’t tried it yet. Please let us know here if you were able to do that, thanks!

      Reply
  18. moiky
    moiky says:

    Right now all i can print is plain text with no format. I need to be able to format printed text to BOLD, Italic and underline

    Reply
  19. Miquel Mas
    Miquel Mas says:

    Maybe this post can help the people who want to print images throught the thermal printer.
    http://stackoverflow.com/questions/14530058/how-can-i-print-an-image-on-a-bluetooth-printer-in-android

    The key is set the correct values to the “public static byte[] SELECT_BIT_IMAGE_MODE” variable

    For my image (380px width) the correct value was

    public static byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 33, 124, 1};

    the first 3 parameters can be the same, the last 2 depends on the image width

    380dec = 00000001 01111100

    01111100 –> to dec = 124
    00000001 –> to dec = 1

    Reply
  20. sureshbabu
    sureshbabu says:

    Hai ninjazhai. Thanks for the bluetooth prinitng code. Can u explain me the concept ‘beginListenForData()’ function.. i.e how it checks whether data is sent for printing.

    Reply
  21. BENIGNO VERA
    BENIGNO VERA says:

    hello BluetoothPrintImage buy the code to print the image but leaving some characters and not print the image, I wonder if I can help with the solution

    Reply
      • BENIGNO VERA
        BENIGNO VERA says:

        It is zebra 220, in the code that I have to change if I can help, I will read the manual of the printer and the resolution you have is 203 bpi, with width of 56mm and 914 mm long.

        Reply
  22. BENIGNO VERA
    BENIGNO VERA says:

    Hi Mike, PLEASE NOSE SI revise the problem that I mentioned AND SEND THAT YOU WANT PRINTER PRINT, IS URGENT PLEASE THANKS

    Reply
  23. Good Citizen
    Good Citizen says:

    This is an awesome tutorial and I really appreciate.
    Now the code is working perfectly, but I can only print once. When I attempt to print the second time, I get the error message below:
    “java.io.IOException: read failed, socket might closed or timeout, read ret: -1”.

    Can someone help me out on fixing this one?

    Thnaks.

    Reply
      • Good Citizen
        Good Citizen says:

        I really appreciate you getting back to me on this.
        I was attemptiong to print dynamically created data from sqlite database. By the time I sent in my feedback, the printer was only printing once however, after abit of tinkering, I moved the closeBT() method to be executed just after the first receipt has been printed, and it is now working.
        Your tutorial has helped me learn alot.
        Thanks a bunch.

        Reply
  24. Ahmed Ibrahimm
    Ahmed Ibrahimm says:

    hi

    i want your help

    i buy new mobile thermal printer

    how can change sdk printdemo
    for printing arabic

    and print images

    Reply
  25. Ahmed Ibrahimm
    Ahmed Ibrahimm says:

    hi mr mike
    i buy mobile thermal printer
    i having problem with printing arabic
    and barcode and images
    can you help me for change sdk

    Reply
  26. Ruth Okoilu
    Ruth Okoilu says:

    Hi, please I need your help. I have implemented your code but on click on the Send button, It does not do anything and no error is shown. I’m using DPP 250 bluetooth printer.

    Reply
  27. Mike Dalisay
    Mike Dalisay says:

    Hello @ahmedibrahimm:disqus, I we talked via email few days ago. It worked with english and chinese characters. You have to contact your printer manufacturer about its configuration for printing arabic characters.

    Reply
  28. Mega Tfive
    Mega Tfive says:

    Hey ! This is great !

    AWESOME JOB MAN !

    i needed this for a project !

    but i am facing a problem, i have another bluetooth printer and its not working with it ?

    Can you help please !

    Reply
  29. Maqsood
    Maqsood says:

    Hi Mike,, I am using hp officejet 100 mobile printer, I am able to send the data but data is not printing in printer Only i can see empty

    Reply
  30. afique
    afique says:

    Thanks for this awesome project! It seems like i can’t print out the message to the printer. here is the log.

    01-26 09:55:43.377 13074-13074/com.hatching.mposprintertwo W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.bluetooth.BluetoothSocket android.bluetooth.BluetoothDevice.createRfcommSocketToServiceRecord(java.util.UUID)’ on a null object reference

    01-26 09:55:43.377 13074-13074/com.hatching.mposprintertwo W/System.err: at com.hatching.mposprintertwo.MainActivity.openBT(MainActivity.java:136)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at com.hatching.mposprintertwo.MainActivity$1.onClick(MainActivity.java:62)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.view.View.performClick(View.java:5204)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.view.View$PerformClick.run(View.java:21153)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.os.Handler.handleCallback(Handler.java:739)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.os.Looper.loop(Looper.java:148)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at java.lang.reflect.Method.invoke(Native Method)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

    01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    what is the problem actually? thanks.

    Reply
  31. elvalelucho
    elvalelucho says:

    Hi, you should be publish the image with you test… publish your superman logo… please for test, because i buyed that code and it’s fail… or give me any specification of the image… png, bmp, gif… size of image, dimentions… thanks for your work!!

    Reply
  32. Enrique Alvarado
    Enrique Alvarado says:

    Hi!, I have a question….

    is this the only version (LEVEL 2) of the downloadable file? I download it time ago and run all ok, (when the page shows a MP300 printer) I lost the file, and download it again, but it don’t run like the last time, is this a newer version? if Yes, could you send me the old version ?

    thanks a lot,

    enrique

    Reply
    • Mike Dalisay
      Mike Dalisay says:

      Hello @disqus_n1f2NimhSp:disqus, source code is almost still the same, the only change is before, I developed it in Eclipse, now it is developed in Android studio. Which one do you use currently? I’ll try to find the old file, please send me an email at mike@codeofaninja.com so I can know your email address

      Reply
  33. amdad hossain
    amdad hossain says:

    hi i have tried this i have a question is if i want to print on another blutooth device is this works????and what i have to do on this way for different printer?

    Reply
  34. kamullick
    kamullick says:

    Thanks for the code. I am trying to implement it with a non-brand POS printer. It’s not connecting. The connect() function leads to Local/Android/sdk/sources/android-22/android/bluetooth/BluetoothSocket.java where I am getting an error “cannot resolve symbol ‘IBluetooth’ ” in the line #301

    IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);

    Being a new programmer, I can’t find a solution. It’d be really nice if somebody helps me out.

    Reply
  35. Rodolfo Ruiz
    Rodolfo Ruiz says:

    HI a have a problem with this code.
    error: “Attempt to invoke virtual method ‘void java.io.OutputStream.write(byte[])’ on a null object reference”
    in this line: mmOutputStream.write(line.getBytes());

    work on android studio 2.1, android version 5.1.1, java jdk1.8.0_91
    thanks for your help

    Reply
  36. Sajid Khan
    Sajid Khan says:

    When there is no paper inside printer but it is connected with device and If I give print command it is showing printing successful but actually it is not printing.

    Reply
  37. PPKX XD ✓ᵛᵉʳᶦᶠᶦᵉᵈ
    PPKX XD ✓ᵛᵉʳᶦᶠᶦᵉᵈ says:

    Hi, does this code supports multiple phones sending print requests to the same printer simultaneously? It’s not clear for me whether the connection should be closed right after printing so other phones can send data do the same printer, or if I can keep like 5 phones connected at the same time.

    Reply
    • Mike Dalisay
      Mike Dalisay says:

      Hello @manowars:disqus , multiple android device can send print requests to the same printer but should be done one at a time. I believe you can connect 5 phones to the same printer at a time but sending print requests at the same time could cause errors.

      Reply
      • PPKX XD ✓ᵛᵉʳᶦᶠᶦᵉᵈ
        PPKX XD ✓ᵛᵉʳᶦᶠᶦᵉᵈ says:

        Thank you.
        I was wondering if I can keep the phones connected to the printer or if I have to disconnect after printing each receipt.I thought that keeping the connection was preventing to print from more than one device at the same time.

        Reply
  38. anil kumar
    anil kumar says:

    Hi, This is great. But I am facing formatting issues, the content is printing continuously not line by line. I think msg += “n”; is not working, could you please suggest how to fix it.

    Reply
    • Yaskin Forrit
      Yaskin Forrit says:

      I’m using a Zebra iMZ printer. This code does not seem to work for me but , I’ve found that you need to put “rn” at the end of every line, not just “n”

      Reply
      • Mike Dalisay
        Mike Dalisay says:

        Thanks for sharing your solution @yaskinforrit:disqus! I’m sure this will be useful for Zebra iMZ printer users!

        If you don’t mind, what error message do you encounter that our code above did not work for you?

        Reply
  39. Juan
    Juan says:

    hello, thank you for proving such a wonderful post, my question is, how would I go about incrementing the text size when print is executed?

    Thank you

    Reply
  40. Sajid
    Sajid says:

    Thanks for your nice tutorial. Is there any way to get notification from printer to mobile that my sending command is not printed properly ?

    Reply
  41. Naresh
    Naresh says:

    Hi, Are you waiting for any acknowledgment here form printer . if yes why it is required? I trying this by using ESC Sequence. but it picking up some random values.

    Reply
  42. Wibson
    Wibson says:

    Would you like to know if this code works on the Knup bluetooth printer (kp-1019)? I want to pay for the code, but I need to make sure it works on the printer I own! Grateful!

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *