Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data to bluetooth printer via android app?

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

like image 859
G K Avatar asked Feb 10 '13 09:02

G K


People also ask

How do I print to a Bluetooth printer from my Android phone?

Connecting the Printer to Your Android DeviceGo to Settings > Wireless & Network and turn on Bluetooth. Wait while your device scans for the printer. The printer is displayed when your device finds it. Tap the printer.

How do I connect my Android app to my printer?

Start your mobile application and tap the Settings icon. (Mobile Cable Label Tool users must also tap [Printer Settings] - [Printer].) Select the printer listed under [Wi-Fi Printer]. You can now print from your device wirelessly.

How do I connect my Android to a thermal printer?

Plug one end of the USB cable into the USB port of the printer, and the other end into the female USB connector of an OTG adapter or cable. Then, plug the micro-USB end of the OTG adapter or cable into the micro-USB port of your mobile device, and wait for the system to recognize the printer.


2 Answers

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);
    }
}
like image 174
G K Avatar answered Oct 06 '22 23:10

G K


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!

like image 25
Sean Avatar answered Oct 07 '22 01:10

Sean