How can i print to thermal bluetooth printer? - android

I develop a mobile point of sale with flutter, but I don't know how to print the receipt on a Bluetooth thermal printer
I currently develop a plugin for it but it doesn't work yet
protected void printBill() {
if(btsocket == null){
btsocket = DeviceList.getSocket();
Intent BTIntent = new Intent(getApplicationContext(), DeviceList.class);
this.startActivityForResult(BTIntent, DeviceList.REQUEST_CONNECT_BT);
Toast.makeText(activity,"tes",Toast.LENGTH_LONG).show();
}
else{
OutputStream opstream = null;
try {
opstream = btsocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
outputStream = opstream;
//print command
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputStream = btsocket.getOutputStream();
byte[] printformat = new byte[]{0x1B,0x21,0x03};
outputStream.write(printformat);
printCustom("Fair Group BD",2,1);
printCustom("Pepperoni Foods Ltd.",0,1);
printCustom("H-123, R-123, Dhanmondi, Dhaka-1212",0,1);
printCustom("Hot Line: +88000 000000",0,1);
printCustom("Vat Reg : 0000000000,Mushak : 11",0,1);
String dateTime[] = getDateTime();
printText(leftRightAlign(dateTime[0], dateTime[1]));
printText(leftRightAlign("Qty: Name" , "Price "));
printCustom(new String(new char[32]).replace("\0", "."),0,1);
printText(leftRightAlign("Total" , "2,0000/="));
printNewLine();
printCustom("Thank you for coming & we look",0,1);
printCustom("forward to serve you again",0,1);
printNewLine();
printNewLine();
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The source code can be found here
Please help me develop this plugin, at least it can print text

I finally created my own plugin
https://pub.dev/packages/blue_thermal_printer

Related

Calculate Speed and Bytes Transfer Rate in FTP download Android

I am planning to create an application for downloading a file from FTP server, Below code has working fine with the functionality, But I need to show current speed and transfer rate while downloading a file, Please help me to solve this problem,
private boolean downloadSingleFile(String remoteFilePath, File downloadFile) {
boolean status = false;
try {
con = new FTPClient();
con.setConnectTimeout(5000);
con.connect(host);
if (con.login(username, password)) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
File parentDir = downloadFile.getParentFile();
if (!parentDir.exists())
parentDir.mkdir();
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(
new FileOutputStream(downloadFile));
con.setFileType(FTP.BINARY_FILE_TYPE);
status = con.retrieveFile(remoteFilePath, outputStream);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
con.logout();
con.disconnect();
}
} else {
con.logout();
con.disconnect();
// delayWait(duration);
}
}
catch (UnknownHostException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
}
return status;
}
If i would like to download a more than 5Mb or 50 Mb file this requirement will be useful for the user to know about the current speed of the device , Please help me to finish this issues.
Regards
Priya

Transfer String from android to pc via bluetooth

Since many days i am going through many examples and questions related to my issue but nothing helps!
Aim
two way communication between pc(windows) and android (like passing msg to pc and acknowledgement from pc)
What i have done till now
I am able to send String to pc(windows) from my android device using bluetooth.
here is the code i used
private String sendFile(String mac_address, String device_name) {
// TODO Auto-generated method stub
String result="";
btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(mac_address);
Log.d("BT_SENDING_FILE",device_name+" "+mac_address);
try {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
btSocket = (BluetoothSocket) m.invoke(device, 1);
if(!btSocket.isConnected()){
Log.d(" is connected Status",""+btSocket.isConnected());
// device.createInsecureRfcommSocketToServiceRecord(UUID);
}
btAdapter.cancelDiscovery();
try{
btSocket.connect();
}catch(IOException e){
btSocket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
btSocket.connect();
Log.d("fall back","in catch clause");
}
byte[] msgBuffer = stringToSend.getBytes();
outStream = btSocket.getOutputStream();
outStream.write(msgBuffer);
if (outStream != null) {
outStream.flush();
}
result = "sent";
outStream.close();
btSocket.close();
Log.d("BLUETOOTH","Closing Socket");
} catch (Exception e) {
System.out.println(e);
Log.d("BLUETOOTH","exception while sending through bluetooth");
result = "failed";
e.getLocalizedMessage();
} finally{}
return result;
}
this is running good without any problem.
Problem
But i am not able to receive any String from pc to android device. I have tried many things
I have tried this
BluetoothSocket socket = null;
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
while (true) {
try {
// Creating a new listening server socket
Log.d("BT", ".....Initializing RFCOMM SERVER....");
mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord("Bluetooth", MY_UUID);
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d("Socket","listening...");
socket = mmServerSocket.accept(120000);
} catch (Exception e) {
}
try {
Log.d("Socket", "Closing Server Socket.....");
mmServerSocket.close();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.d("BT","IO stream init");
DataInputStream mmInStream = new DataInputStream(tmpIn);
DataOutputStream mmOutStream = new DataOutputStream(tmpOut);
// use the Input Stream to take the string from the client whoever is connecting
//similarly use the output stream to send the data to the client
StringBuilder sb = new StringBuilder();
while((ch = mmInStream.read())!= -1)
sb.append((char)ch);
String res = sb.toString();
Log.d("BT",res);
tv_response.setText(res));
} catch (Exception e) {
//catch your exception here
e.printStackTrace();
Log.d("Exception","some thing went wrong");
e.getLocalizedMessage();
}
}
}
I am using Blue Cove in windows. I HAVE GONE THROUGH BLUETOOTH CHAT SAMPLE PROJECT but dont understand any thing
your help is appreciated
thank you
i tried following code and it was successful. it may help you
BluetoothSocket socket = null;
while (true) {
try {
Log.i(ACCEPT_TAG, "Listening for a connection...");
socket = mServerSocket.accept();
Log.i(ACCEPT_TAG, "Connected to " + socket.getRemoteDevice().getName());
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
try {
// Read the incoming string.
String buffer;
DataInputStream in = new DataInputStream(socket.getInputStream());
buffer = in.readUTF();
Intent i = new Intent(MESSAGE_RECEIVED_INTENT);
i.putExtra("Message", String.format("%s", buffer));
Log.d("BT response is",buffer);
c.sendBroadcast(i);
} catch (IOException e) {
Log.e(ACCEPT_TAG, "Error obtaining InputStream from socket");
e.printStackTrace();
}
try {
mServerSocket.close();
} catch (IOException e) { }
break;
}
}
Be sure that your device is visible to all i.e scan mode is BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE
else use this code
public void requestBTDiscoverable() {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivityForResult(i, REQ);
int result = 0;
this.onActivityResult(REQ, result, i);
Log.i(TAG, "Bluetooth discoverability enabled");
}

Android socket connect freezing

I am trying to implement a simple socket that sends and receives strings from a server.
The following code is freezing the application, not sure if I have done something obviously wrong?
public String internetRoutesRetrieve(String userName) {
String command = null;
String response = null;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("Hidden IP", HiddenPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
command = "SEARCH <" + userName + ">";
dataOutputStream.writeUTF(command);
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
Thanks
Edit: It seems the program is freezing when I am trying to save the response from the server
see AsyncTask for proper client server communication on Android application.
you'd usualy get android.os.NetworkOnMainThreadException if you don't but I'd give it a try.

Android Printing via Bluetooth SPP

I need to print plain text in my android application. As far as I can tell I need to create an socket with SPP UDID to my device.
The sample codes I've seen, people just get an OutputStream from the Socket and the push the string with the text they want to print.
Is is that simple? Just push text through OutputStream?
Try this for print text:
try {
Socket clientSocket = null;
DataOutputStream outToServer;
try {
clientSocket = new Socket("192.168.101.64", 9100);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeUTF("Some string to print");
}
outToServer.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}

Android udp port

i want to send a udp packet from my laptop to an android device, i write a simple App for that but it doesn't work, i think that the port(5554) that i have been used is the problem.
Code:
`private void runUdpServer()
EditText RecieveText = (EditText) findViewById(R.id.editText1);
EditText check = (EditText) findViewById(R.id.editText2);
String lText;
byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
DatagramSocket ds = null;
RecieveText.setText("try1");
try {
RecieveText.setText("try2");
ds = new DatagramSocket(UDP_SERVER_PORT); // i think the problem is here
//disable timeout for testing
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
RecieveText.setText("try");
ds.receive(dp);
lText = new String(lMsg, 0, dp.getLength());
Log.i("UDP packet received", lText);
RecieveText.setText(lText);
check.setText("port opened");
} catch (SocketException e) {``
check.setText("SocketException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
check.setText("port didn't open");
} finally {
if (ds != null) {
ds.close();
RecieveText.setText("not connected1");
}
else {RecieveText.setText("not connected1");}
}
check.setText("end");
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
}
}
I dont think it is a port issue... print your error log to have a better idea of faillure.... any way try this ... not checked for any typo.... Also keep in mind that any networking task is better to be inside an async task...
int port =1855; ///any port that you want > 1024
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
//////send socket
int eport = 1616;
InetAddress eip = null;
try {
eip = InetAddress.getByName("192.168.1.1"); ////SERVER IP ADDRESS
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramSocket esocket = null;
try {
esocket = new DatagramSocket(eport);
} catch (SocketException e) {
e.printStackTrace();
}
///SENDING
byte[] send= new byte[60*1024];
DatagramPacket send_packet = new DatagramPacket(send, send.length);
try {
socket.send(send_packet);
} catch (IOException e) {
e.printStackTrace();
}
//////Start receive
while(true)
{
byte[] message = new byte[60*1024];
DatagramPacket recv_packet = new DatagramPacket(message, message.length);
try {
socket.receive(recv_packet);
} catch (IOException e) {
e.printStackTrace();
}
///Do something whit recv_packet
}

Categories

Resources