15

I am developing an app which will send data to a printer via bluetooth to print (A thermal printer for receipts). I have followed the code which in this link.

http://pastie.org/6203514 and this link also http://pastie.org/6203516

I am able to see the device and its MAC Address and its name, when I send the data to the printer (the light LED on the printer stops blink and becomes standard i.e the printer is connected with my android phone) but when I send the data it is not printing and nor it is giving any error also. I have googled a lot and I found many codes and tried all set of codes but could not able to print .

Please any one could help me out of here. I heard with Intents it can be done easily but could not get the exact solution with Intents.

Any help would be appreciated Thanks in Advance

Ganesh

G K
  • 2,481
  • 4
  • 29
  • 45

2 Answers2

10

Finally I solved this problem by my self and the problem is that the header byte which I am sending to the printer is the real culprit. Actually I am sending 170,1 (where 170 is the first byte that the printer must receive and the second byte is the printer id I mean some com port which these two values are given by Printer control card designer). Actual I have to send 170,2 where 2 is the Printer Id so that it gives the correct print and for every printer it is common of sending the data based on their control card's.

Thanks a lot friends and here is my code that u can use these code for all types of printers(for POS-Thermal Printers)

public void IntentPrint(String txtvalue)
{
    byte[] buffer = txtvalue.getBytes();
    byte[] PrintHeader = { (byte) 0xAA, 0x55,2,0 };
    PrintHeader[3]=(byte) buffer.length;
    InitPrinter();
    if(PrintHeader.length>128)
    {
        value+="\nValue is more than 128 size\n";
        txtLogin.setText(value);
    }
    else
    {
        try
        {
            for(int i=0;i<=PrintHeader.length-1;i++)
            {
                mmOutputStream.write(PrintHeader[i]);
            }
            for(int i=0;i<=buffer.length-1;i++)
            {
                mmOutputStream.write(buffer[i]);
            }
            mmOutputStream.close();
            mmSocket.close();
        }
        catch(Exception ex)
        {
            value+=ex.toString()+ "\n" +"Excep IntentPrint \n";
            txtLogin.setText(value);
        }
    }
} 

And this code for the rest:

public void InitPrinter()
{
    try
    {
        if(!bluetoothAdapter.isEnabled())
        {
           Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
           startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("Your Device Name")) //Note, you will need to change this to match the name of your device
                {
                    mmDevice = device;
                    break;
                }
            }

            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
            //Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
            //mmSocket = (BluetoothSocket) m.invoke(mmDevice, uuid);
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
            bluetoothAdapter.cancelDiscovery();
            if(mmDevice.getBondState()==2)
            {
                mmSocket.connect();
                mmOutputStream = mmSocket.getOutputStream();
            }
            else
            {
                value+="Device not connected";
                txtLogin.setText(value);
            }
        }
        else
        {
            value+="No Devices found";
            txtLogin.setText(value);
            return;
        }
    }
    catch(Exception ex)
    {
        value+=ex.toString()+ "\n" +" InitPrinter \n";
        txtLogin.setText(value);
    }
}
Jorge B.
  • 1,144
  • 2
  • 17
  • 37
G K
  • 2,481
  • 4
  • 29
  • 45
  • One question. Sorry for reviving an old post. "blueToothDevice" refers to the name of the activity, correct? – Razgriz Jul 06 '13 at 17:14
  • Ah never mind that previous question. I'm getting the "Exception 1" at the Try Catch statement in the CheckLogin() function. – Razgriz Jul 07 '13 at 02:06
  • What exception you are getting and in CheckLogin() what exception u r getting? Can u post it here or use pastie.org. @Razgriz and blueToothDevice is for holding the devices name. – G K Jul 07 '13 at 10:45
  • I got to connect to the thermal printer, however, I had to change a line to `BluetoothSocket socket = (BluetoothSocket) m.invoke(blueToothDevice, 1);` for the Bluetooth light on the device to light up. However, I could not successfully send data to the printer for printing. When exactly do I call IntentPrint? – Razgriz Jul 08 '13 at 08:29
  • I managed to make it work. It's now printing a newline, I have to clean my code up since I dumped a LOT of write statements. The problem was with the hardware, there was an instruction in the manual regarding the DIP Switches of the device. – Razgriz Jul 09 '13 at 02:30
  • InitPrinter() function is for connecting to our bluetooth printer and IntentPrint() is the code for actual printing. It should be called when you have all the data to print and then call the method by passing a string. What exactly you are getting a problem and if u need any more help in code I will just post the entire code of procedure again in some blog and give u link @Razgriz – G K Jul 26 '13 at 03:36
  • @Ganesh I am also facing the problem to send the data to printer..the device connect to the printer but unable to pass the data for printing – Manish Aug 24 '13 at 07:29
  • @Ganesh can u plz explain it with hole code..Thanks in advance – Manish Aug 24 '13 at 07:43
  • Intent Print method is the main method which is used for printing via bluetooth printer, for that u just need to call the IntentPrint() method where ever u need to print and just pass the string to the method. In my case the command code for my printer is 170,85,2,0. This is the command code I must send every time I print. Then in next statement I am passing the converted string to print. If you know the command code for your printer, then your problem is solved almost or else just refer to @Sean post below for generic printer.@Manish – G K Sep 02 '13 at 13:28
  • Can u please tell me that how to connect printer with tablet with wifi???..............Thanks in advance – Denny Sharma Oct 28 '13 at 12:25
  • @DennySharma I hope this link might helps you http://stackoverflow.com/questions/6708804/android-esc-pos-printing-over-wifi – G K Dec 10 '13 at 05:18
  • @GK, with code you've provided I'm able to to connect to printer it also rolls the paper but prints nothing on it. Any idea what would be problem? btw, thank you for code :) – Farid Feb 11 '17 at 11:02
  • @FARID When you send the byte array to the printer, as soon as it receives the signal, it returns the first one/two bytes back back to your code to say that the communication has established. In your case hope you should be getting the byte back from your printer. – G K Feb 14 '17 at 06:13
  • Can you able to post your code and share the link here, will have a look into it although I don't have the above code with me, but I still have little idea about it as it was more than couple of years since I touched these code. @FARID – G K Feb 14 '17 at 06:14
  • @GK Hi, appreciate your reply. I contacted HP support team. Fortunately, HP (Officejet H470) supports .jpeg file format, I just shared .jpeg format file with printer via Bluetooth instead of sending it in byte array and it printed the content. – Farid Feb 14 '17 at 13:03
  • `Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setComponent(new ComponentName( "com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity")); intent.setType("image/jpeg"); /*Uri uri = Uri.fromFile(getOutputMediaFile());*/ intent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(intent);` – Farid Feb 14 '17 at 13:03
  • That's great @FARID – G K Apr 05 '17 at 09:06
  • Can anyone help for bitmap printing using bluetooth printer? – Muhammad Umair Shafique May 02 '17 at 07:04
  • @MuhammadUmairShafique hope you can convert it to an byte array and then use the above code to send data to printer. I am hoping it might work. Give a try. – G K May 03 '17 at 05:11
  • @GK i have tried to do same by converting bitmap to byte array but this code is printing bytes on page instead of image. Please suggest me some solution – Muhammad Umair Shafique May 03 '17 at 05:26
1

Are you aiming for a specific protocol of printing? (for specific printer?)

If not, and a generic print can be made to whetever printer is connected, you can use this code snippet:

Write this where you want to print a specific file/files:

            Intent intent = Tools.getSendToPrinterIntent(
                    DisplayActivity.this, mPdfAsPictures,
                    mPrintCurrentIndex);

            // notify the activity on return (will need to ask the user for
            // approvel)
            startActivityForResult(intent, ACTIVITY_PRINT);

This is the helper method:

public static Intent getSendToPrinterIntent(Context ctx, String[] fileFullPaths, int indexToPrint){
    Intent sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);

    // This type means we can send either JPEG, or PNG
    sendIntent.setType("image/*");

    ArrayList<Uri> uris = new ArrayList<Uri>();

    File fileIn = new File(fileFullPaths[indexToPrint]);
    Uri u = Uri.fromFile(fileIn);
    uris.add(u);

    sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

    return sendIntent;
}

And finally, you'll receive the answer at:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ACTIVITY_PRINT) {

        switch (resultCode) {
        case Activity.RESULT_CANCELED:
            Log.d(TAG(), "onActivityResult, resultCode = CANCELED");
            break;
        case Activity.RESULT_FIRST_USER:
            Log.d(TAG(), "onActivityResult, resultCode = FIRST_USER");
            break;
        case Activity.RESULT_OK:
            Log.d(TAG(), "onActivityResult, resultCode = OK");
            break;
        }
    }
};

Good luck!

Sean
  • 5,176
  • 2
  • 34
  • 50
  • Thanks for your code. The first block of code u have posted is to connect to printer to print the data. so I have to detect the printer and get its MAC address. right? and next block of code is the function implementation. but in your code there is nothing tagged with any printer for sending the data. Did u check out my code which I posed in above link. @Sean – G K Feb 10 '13 at 10:10
  • 1
    @Ganesh The code I've provided is to send data when you don't know the exact printer you are going to use. It's like the "share" intent where you don't know which applications can share data. http://developer.android.com/training/sharing/send.html – Sean Feb 10 '13 at 10:14
  • I want to print some string for that what should I repalce in first block of code Tools.getSendToPrinterIntent( ***,here also, here and here); and Where is the "Tools" came from If possible Can you come in chat? I need some clarifications. – G K Feb 14 '13 at 11:20
  • When I used my code I got this new type exception before this statement mmOutStream.write(bytes); Exception: Host is down and some times Software caused Connection abort exception" What shall I need to do? Does my code goes wrong any where? Please tell me on how to modify with my code and not with new code Plese. – G K Feb 14 '13 at 12:55