Android Bluetooth Printing

I am writing an application that sends data to a bluetooth printer. Can someone help me? how can i use bluetooth stack for android? or is there an external api or sdk to use?

Here is my bluetooth search code ...

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); btArrayAdapter.add(device.getName() + "\n" + device.getAddress()); btArrayAdapter.notifyDataSetChanged(); } } }; 

and here is my code to send data to the printer.

 BluetoothDevice mDevice = bluetoothAdapter.getRemoteDevice("00:15:FF:F2:56:A4"); Method m = mDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); mBTsocket = (BluetoothSocket) m.invoke(mDevice, 1); System.out.println("Connecting....."); mBTsocket.connect(); System.out.println("Connected"); OutputStream os = mBTsocket.getOutputStream(); os.flush(); os.write(Receipt.getBytes()); // mBTsocket.close(); 

When I write socket.close (), the data does not get printed to the printer, since the socket is closed before printing the data .. and if I did not write socket.close (), then the data is printed only once .. I could not print the data a second time until I restart the bluetooth of my phone.

can anyone have a solution? or is there any other way to get rid of this seal?

+7
source share
2 answers

I have a solution to my problem ...

if I want to print data more than once, then you do not need to create a new Socket connection with the device ... instead, the outputstream.write (bytes) method is called.

and in the end, if you want to disconnect the device, call the mBTScoket.close () method to disconnect the device.

+5
source

If you have established a connection with devices and paired it.

So, for printing, the printer wants to get a byte. So I created mothod.

Just call this method and pass the line inside it to print.

String str = new String("This is the text sending to the printer");

 private void printData() { // TODO Auto-generated method stub String newline = "\n"; try { out.write(str.getBytes(),0,str.getBytes().length); Log.i("Log", "One line printed"); } catch (IOException e) { Toast.makeText(BluetoothDemo.this, "catch 1", Toast.LENGTH_LONG).show(); e.printStackTrace(); Log.i("Log", "unable to write "); flagCheck = false; } try { out.write(newline.getBytes(),0,newline.getBytes().length); } catch (IOException e) { Log.i("Log", "Unable to write the new line::"); e.printStackTrace(); flagCheck = false; } flagCheck = true; } 
-one
source

All Articles