Android Bluetooth Printing Example Code with Actual Printer Device

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.

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.


288 responses to “Android Bluetooth Printing Example Code with Actual Printer Device”

    • 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? :)

  1. Bluetooth program i try to add multiple text field that time i try to open Bluetooth but it is not open why?

      • BUFFER ISSUE ??
        I use several mmOutputStream.write in my app,
        i.e. one by ‘printer command’, line to print, … but I have problem that not always all my requests seem to be sent to the printer. Can it be I must do all in one write only ??

    • 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…

        • Hi @Marwen, you can get the name of the device when you open it and your phone scans the available bluetooth device. You might find it in the packaging of your bluetooth printer device.

  2. 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

  3. 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

  4. 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)

      • 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

          • 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

          • 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 .

          • 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

          • 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

          • 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

          • 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

          • 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.

  5. 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..

  6. 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

  7. 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

  8. 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

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

    And not performed on. Pleas help!

  10. 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

    • 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

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

  11. 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 .

    • 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.

      • 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!

  12. @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!

  13. 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.

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

  15. 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.

    • 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);

    • 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);

  16. 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.

  17. 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)

    • 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.

    • java.lang.NullPointerException

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

  18. 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

  19. This is great tutorial, thanks .
    Does any one know how i can format the print output to Bold, Italic and underline.

    • 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!

  20. 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

  21. 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

  22. 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.

  23. 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

      • 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.

  24. hi thanks for reply, it is a zebra rw 220 printer prints this way, I can change in the code, if I can help.

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

  26. 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.

      • 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.

        • Hello Good Citizen, I was trying to print dynamically created data from sqlite database, but I don’t know how to change the code of Mike Dalisay to do it. Do you convert your data in a file or something like that. I would appreciate a lot your reply.

          Thanks a lot.

          Tony

          • No.
            Actually, as per Mike’s code, there is a variable msg. I get the records from the SQLite database, and assign them to that variable msg. The contents of msg is what I print out, and it is working perfectly.

  27. hi

    i want your help

    i buy new mobile thermal printer

    how can change sdk printdemo
    for printing arabic

    and print images

  28. 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

  29. 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.

  30. 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.

  31. 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 !

  32. 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

  33. 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.

  34. 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!!

  35. 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

    • 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

    • Hello @disqus_KRrNtzO1Tm:disqus, unfortunately, I don’t have that kind of printer. The best way to know if it will work is to test the source code with your printer.

  36. 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?

  37. 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.

  38. 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

  39. 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.

      • Hello, yeah. But, as the mobile is connected with printer it always shows print successful though it is not printing for unavailability of paper.

  40. 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.

    • 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.

      • 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.

  41. 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.

    • 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”

      • 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?

  42. 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

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

  44. 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.

  45. 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!

    • Unfortunately, we are unable to test it on that kind of printer because we don’t have one. We only tested the code on the printer above. Download at your own risk.

  46. Great tutorial, definately gonna try it..
    I have a question, is it possible to print a PDF by this code?

  47. HI, where does the binding actually happen? In findBT() you do Set pairedDevices = mBluetoothAdapter.getBondedDevices(); but that won’t return anything if no devices actually bonded with the device, correct?

  48. Excelente!, gracias amigo funciona a la perfección solo cambiando el nombre del dispositivo Bluetooth Mil gracias

  49. Hi ,

    We are looking for driver for following device below and need to print PDF doc from tablet to printer.

    Printer: Bluetooth Printer SEWOO LK-P30
    Tablet: Samsung SM-T231, Galaxy Tab4 7.0 3G (Android OS, v4.4.2 (KitKat))

    Thanks waiting for your reply

  50. Hi. when i implement your code it seems that the send and close button is not working. whenever i click the sent button it has an error java.lang.NullPointerException: Attempt to invoke virtual method ‘void java.io.OutputStream.write(byte[])’ on a null object reference. The open button is working. I used 2 printer. 1 thermal printer and 1 dot matrix printer and both of the printer is not working. Can you help me? thank you.

  51. java.lang.NullPointerException: Attempt to invoke virtual method ‘void java.io.OutputStream.write(byte[])’ on a null object reference

  52. Hi,
    did anyone try to do something similar in App Inventor 2. i.e print some text from Android phone to a bluetooth thermal printer?

    thanks in advance for any details.

  53. hi ,
    this is for the input text but i just want to print the whole data near about 2 page .Then for that please give me some code. with that i can print my dynamic data. if it is paid then tell me.

  54. hi! I have a printer DPP 250, the program is working good.. and conncet whith the printebut the print does not come out! plis help

  55. Excellent tutorial!
    Is there anybody who is able explain that why used this uuid “00001101-0000-1000-8000-00805f9b34fb” ?

  56. Hey how can I list the paired device on a builder and then when I click on a device it connect to the selected device?

  57. Hello Friend! Do you have a code where I can increase the size of the character to be displayed? I have a small project here, but the default font size on the printer does not please the client …

  58. Hello there, I have tried this source code (level 1), everything is working well until the part where I have to send Data to the printer. There the exception happens i.e. Java.IO.IOException: Broken pipe.
    I have no idea what is wrong with it. I am trying to deploy this code in Xamarin C# Android.

    Any help will be appreciated thanks.

  59. Hello Mike , Great work ! Appreciate it . But I was wondering the way to do the same thing via a wifi printer. Will you be able to provide the way to scan the wifi printer and send the data to be printed? Hope to hear from you soon.

  60. android java.lang.nullpointerexception attempt to invoke virtual method ‘voidjava.io.outputstream.write(bytes[])on null object ref

    getting this error

  61. Hello, Just copied this code and run. It shows the paired devices and shows “Bluetooth device found” in EditText field. Things worked well upto socket creation but on connect() call exception occurs like this ” read failed, socket might closed or timeout, read ret: -1 “. Please help !!!
    Many thanks.

  62. Your code works well in ESC/POS mode, but when I tested it in TPCL mode on my Toshiba B-EP4 DL, it also looks like send data to the printer, but it just doesn’t print anything.
    I am trying to write an APP to print in TPCL mode. I have fount tens of code blocks that work well in ESC/POS but nothing to print in TPCL via Bluetooth.

  63. Hello There, i have bought your source code for Android Bluetooth Printing Source Code – LEVEL 2 Source Code on Code Ninja. Order ID#24989. I haven’t received any download link. Please send me the link.

  64. Hi I just buy your source code, but I am new to android studio and it says need to change property about androidx how should i do it best regards,
    Nathan

  65. Hello, I am interested to buy the source, please let me know some details:
    1. is there complete java source code in clear included, includine the source code of the library?
    2. is there a list of supported BT printers?
    3. does it works also with WiFi printers?
    4. how can I purchase and how will I receive the source code?
    5. does it print to 50mm and 80mm BT printers?
    6. does it print Barcode & QR code?
    Thank You.

  66. Hello. Very good tutorial.
    I have successfully implemented your code, but now I want to print a label in code39 barcode. Do you have the java code?
    Thanks for your help. Greetings.

  67. Hello, I would like to buy this code. Is there any new updated version that I will get?

    Is it possible to print many rows (restaurant bill) without buffer problems?

Leave a Reply

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