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();
}
Related
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
I'm developing an Android app that is going to send camera stream to a Node.js web server by Socket. When the app has to create the socket the app doesn't execute the code inside the try statement but even though launchs any catch exception.
MyThread.java
protected Void doInBackground(Void... unused) {
OutputStream os = null;
try {Log.d("MyCameraApp", "HERE1");
mSocket = new Socket(ip, port);
if (mSocket != null) {Log.d("MyCameraApp", "SOCKET CONNECTED");
try {
os = mSocket.getOutputStream();
while (true) {
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(4);
dos.writeUTF("####");
dos.writeInt(mFrameBuffer.size());
dos.writeUTF("-##-");
dos.flush();
dos.write(mFrameBuffer.toByteArray());
dos.flush();
Thread.sleep(1000 / 15);
}
} catch (Exception e) {
e.printStackTrace();
try {
if (os != null)
os.close();
} catch (Exception e2) {
e.printStackTrace();
}
}
}
else {
Log.d("MyCameraApp", "SOCKET NULL");
}
}
catch(UnknownHostException e) {
Log.d("MyCameraApp", "CATCH SOCKET");
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
CameraActivity.java
try {
mThread = new MyThread(getApplicationContext(), SERVERIP, SERVERPORT);
mThread.execute();Log.d("MyCameraApp", "WELL DONE");
}
catch(Exception e) {
e.printStackTrace();
Log.d("MyCameraApp", "CATCH");
}
The CameraActivity create a mThread object and the app only displays the log 'HERE1' inside the try, before the socket is created and then displays the log 'WELL DONE'.
I have a basic Node.js server that only is listening in the correspondent port, nothing else.
What is wrong?
Thanks in advance!
The Android device was connected by wifi and the pc was connected by Ethernet... differents subnets.
I have set up a server on my computer in java, and the client is my android phone.
I am trying to simulate the mouse behavior in my app but the problem is even though at the first minutes everything runs smoothly, in the end there is a huge delay between client and server.
Server code
try {
System.out.println(InetAddress.getLocalHost());
serverSocket = new ServerSocket(4444); // Server socket
serverSocket.setReceiveBufferSize(10000);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
try {
clientSocket = serverSocket.accept(); // accept the client connection
System.out.println("connection initiated");
DataInputStream din = new DataInputStream(clientSocket.getInputStream());
DataOutputStream dout= new DataOutputStream(clientSocket.getOutputStream());
/* do my things here */
din.close();
dout.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading "+ex);
}
Client code
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
//Inet4Address.getLocalHost().toString(); //InetAddress.getLocalHost().getHostAddress().toString();
System.out.println(dstAddress);
socket = new Socket(dstAddress, dstPort);
socket.setSendBufferSize(10000);
DataInputStream din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF(kappa);
response = "sent to server";
String msg = din.readUTF();
response += msg;
din.close();
dout.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = e.toString();
}
return null;
}
(kappa is a global string that i modify each time.)
What might be the case?
Problem is solved, i changed to udp connection and now there is no delay
I tested many ways and finally asked this question. as many of articles mentioned in wifi-direct all clients know group owner's IP and can use this ip to send a message and group owner will save clients ip address. but I can't send a message from group owner to client like that client sent first time. I faced with this error's:
first:
failed to connect to /192.168.49.24 (port 8988) after 5000ms: isConnected failed:
EHOSTUNREACH (No route to host).
after change code:
first error + bind failed: EADDRINUSE (Address already in use).
My AsyncTask to retrieve :
#Override
protected String doInBackground(Void... params) {
ServerSocket serverSocket = null;
Socket client = null;
DataInputStream inputstream = null;
try {
serverSocket = new ServerSocket(8988);
client = serverSocket.accept();
inputstream = new DataInputStream(client.getInputStream());
String str = inputstream.readUTF();
String IP = client.getInetAddress().toString();
serverSocket.close();
return IP+"+"+str;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}finally{
if(inputstream != null){
try{
inputstream.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(client != null){
try{
client.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(serverSocket != null){
try{
serverSocket.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
}
}
and my IntentService to send messages:
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_IP)) {
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Log.e("DAVUD","Host:"+ host);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Log.e("DAVUD","Port:"+ port);
DataOutputStream stream = null;
try {
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
stream = new DataOutputStream(socket.getOutputStream());
String str = intent.getStringExtra("message");
stream.writeUTF(str);
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
and some other codes I tested... There is another question asked same this but not answered(android-wifi-direct-how-to-send-data-from-group-owner-to-the-clients) this project based on wifiDirectDemo Simple. Please help I really need it.
After one year I sew my question again. the problem was not about wifi or connection. it's about string parsing. where a line in doInBackground is:
return IP+"+"+str
and in onPostExecute I parsed and get ip from returned string; but parse code was not correct. so returns:
192.168.49.24
instead of:
192.168.49.241
where two of them is valid ips I am not thought parse logic had problem. I changed code and used String[] instead of String.
I want to include feature in my android app to print image from network printer through WiFi. I tried below code, posted on stackoverflow, but I am only able to print text :( What to do if I want to print images.
try
{
Socket sock = new Socket("192.168.1.222", 9100);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.println("HI,test from Android Device");
oStream.println("\n\n\n");
oStream.close();
sock.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}