How to print data from Android app to WIFI printer? - android

I am developing shopping cart application in Android 2.1 . I want to print the order details ( customer details , cart details, order total) , when user submit the order . I want to use some WIFI printer for printing the data. Please help me with suitable examples ...

I assume you want to print on receipt-sized paper. If so, Star Micronics has an Android SDK with support for Wifi connections as well as USB and Bluetooth. Download it here: http://starmicronics.com/support/sdkdocumentation.aspx
If you're looking for a regular size printer, check out Google Cloud Print: https://developers.google.com/cloud-print/?hl=en

Create a Socket connection from ip address and port number.
String ip = "your printer ip address";
int port = port number;
private class printTCP extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
if (!ip.equals("")) {
if ((pref.getString(Const.PORT_CASH) != null) && (!pref.getString(Const.PORT_CASH).equals(""))) {
port = Integer.parseInt(pref.getString(Const.PORT_CASH));
try {
client = new Socket(ip, port);// ip address and port number of ur hardware device
String text = "Test Print";
byte[] bytes = text.getBytes(); //create a byte array
outputStream = client.getOutputStream();
outputStream.write(bytes, 0, bytes.length); //write file to the output stream byte by byte
outputStream.flush();
outputStream.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
}

Related

How to print to a Bluetooth printer from a .Net Maui Android app

I want to connect a Maui Android app to a bluetooth printer and print simple text to it. The printers should be treated as generic - there should not be a need to have dedicated SDKs for each printer model.
Using the following code I can connect to the Bluetooth printer.
const string ArduinoBluetoothTransceiverName = "MPT-II";
var connector = DependencyService.Get<IBluetoothConnector>();
connector.Connect(ArduinoBluetoothTransceiverName);
Printing is the main challenge.
Thanks to #Jason. using .Net Maui Andriod app with net7 I can connect to a generic Bluetooth printer and print simple text.
public async Task Print(string deviceName, byte[] imageData)
{
using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
{
MemoryStream stream = new MemoryStream();
BluetoothDevice device = (from bd in bluetoothAdapter?.BondedDevices
where bd?.Name == deviceName
select bd).FirstOrDefault();
try
{
using (BluetoothSocket bluetoothSocket = device?.
CreateRfcommSocketToServiceRecord(
UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
{
bluetoothSocket?.Connect();
stream.Write(imageData, 0, imageData.Length);
// stream.Write(SELECT_BIT_IMAGE_MODE, 0, SELECT_BIT_IMAGE_MODE.Length);
var bytes = stream.ToArray();
bluetoothSocket?.OutputStream.Write(bytes, 0, bytes.Length);
bluetoothSocket.Close();
}
}
catch (Exception exp)
{
throw exp;
}
}
}

Android, accessing device IP address using "Inet4Address.getLocalHost().getHostAddress();" throws exception

so I have an app that is running and on startup, I would like to be able to Get the IP address and display it as a String. I have been using the code below.
String ipAddress = "";
try{
ipAddress = Inet4Address.getLocalHost().getHostAddress();
}
catch(Exception e){
ipAddress = "IP address Cant be used";
}
every time this is run it will return "IP address Cant be used" so it's throwing an error.
If you are looking to get your public facing IP check out this answer. In short you cannot get your public facing IP because the Network Address Transation does not happen in your Kernel, i.e you dont assign your IP to yourself rather it will be given to you thanks to NAT and DHCP. The following code makes a request to amazons's aws IP API, to retrieve your IP
public static String getIp() throws Exception {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
return ip;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

WiFi P2P Connection user interaction bypass?

I am working on an Android application using WiFi Direct. The application is supposed to create a group in each device or search for peers and transfer a string to each peer, depending if the device has Internet connection or not. Also I'm able to discover the MACs of all nearby peers in case the device has Internet.
This is my code for getting the nearby devices, where groupCreated is a variable that states if this device has created a group via createGroup() or is indeed looking for peers:
private WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if (!groupCreated) {
Collection<WifiP2pDevice> refreshedPeers = peerList.getDeviceList();
String peerInfo = "Available peers: \n";
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
for (WifiP2pDevice peer : peers) {
peerInfo += "\nMAC: " + peer.deviceAddress + " - Name: " + peer.deviceName;
}
TextView peerDisplay = (TextView) findViewById(R.id.peerListText);
peerDisplay.setText(peerInfo);
connectPeers();
}
if (peers.size() == 0) {
Toast.makeText(ProviderActivity.this, "No peers found!",
Toast.LENGTH_SHORT).show();
}
}
}
};
This is the code for actually connecting to the peers:
public void connectPeers(){
for (WifiP2pDevice peer : peers) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = peer.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
String host = "192.168.69.1";
int port = 8888;
int len;
Socket socket = new Socket();
String sent = "Hi!";
byte buf[] = new byte[1024];
try {
/**
* Create a client socket with the host,
* port, and timeout information.
*/
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), 1000);
/**
* Create a byte stream from a JPEG file and pipe it to the output stream
* of the socket. This data will be retrieved by the server device.
*/
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = new ByteArrayInputStream(sent.getBytes(Charset.forName("UTF-8")));
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
System.out.println(e.toString());
}
/**
* Clean up any open sockets when done
* transferring or if an exception occurred.
*/ finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
Toast.makeText(ProviderActivity.this, "Failed to close the connection!",
Toast.LENGTH_SHORT).show();
}
}
}
}
}
#Override
public void onFailure(int reason) {
Toast.makeText(ProviderActivity.this, "Failed to connect to peer!",
Toast.LENGTH_SHORT).show();
}
});
}
}
This is the client side, the server side is an async task, taken from https://developer.android.com/guide/topics/connectivity/wifip2p.html#setup in the "Transferring Data" section. Since I always connect to group owners I hardcoded the IP address Android attributes to a GO in WiFi Direct (192.168.69.1).
With this code I'm able to create the group and connect to the peers, but when I try to create a socket and transfer data, in the peers a prompt appears for the user to accept or decline the connection. In the API guide there was no user interaction involved. What am I doing wrong?
Thanks for the attention.
Similar question here.
You can track the numerous requests for this feature here.
And finally, one work around for this that i found in one of the comments in the second link i shared. Read the comments in the given code carefully.

Android UDP server does not receive packets

I have the following code to receive UDP packets:
public class AsyncReceiveUdp2 extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... f_url) {
int udp=111;
byte[] packet = new byte[2000];
DatagramPacket dp = new DatagramPacket(packet, packet.length);
DatagramSocket ds = null;
try {
ds = new DatagramSocket(udp);
ds.receive(dp);
//...
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
return null;
}
}
I send UDP data to computer from Android device.
Computer immediately sends response as UDP packet.
I save information to my log file on SD.
And I see, that my app stays on the line "ds.receive(dp);" and does not run after it.
I've tested on the Android device against a program on computer.
As I understand it is tricky to receive UDP packets on Emulator.
I could not do it.
Redirect does not work for me as it is described here
Another important issue is to receive all packets, that were sent to the device. Lossless. How to modify the code for that?
Please help! Thanks!
put your receive inside a while(true) loop. When you receive a packet call an if (pkg_received){break;}... or whatever you want to do...
The problem is that you are probably only be receiving one package and you are getting timeout before receiving it.
Code edited and not tested
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();
}
Log.d("UDP", "S: Receiving...listening on port " + recv_packet.getPort() );
String rec_str;
rec_str=new String(recv_packet.getData)
Log.d("PACKAGE LENGTH",Integer.toString(recv_packet.getLength()));
}

Android print text on printer

I am developing a restaurant app which print receipts after customer purchases foods. I have added a config screen in app which the manager uses to configure printers. A manager can print a test page to test whether he has entered right ip and port. Here is my code which prints test page:
private class PrintTask extends AsyncTask<Printer, Boolean, String> {
#Override
protected String doInBackground(Printer... params) {
try {
publishProgress(true);
Socket sock = new Socket(params[0].getIp(), Integer.parseInt(params[0].getPort()));
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.printf("--------------------------------\r\n");
oStream.printf("*** TEST PRINT ***\r\n");
oStream.printf("You have configured your \n\r");
oStream.printf(params[0].getName());
oStream.printf("\r\nprinter successfully\n\r");
oStream.printf("| Thanks |\r\n");
oStream.printf("--------------------------------\r\n");
oStream.close();
sock.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(false);
return "";
}
#Override
protected void onProgressUpdate(Boolean... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if(!values[0]) {
waitView.setVisibility(View.GONE);
}
else {
waitView.setVisibility(View.VISIBLE);
}
}
}
The problem is if I print on a network printer (a stand alone printer without attaching to any PC) it prints text properly. Here I am using the ip and default port 9100. But when I print to a shared printer attached to a PC, it fails to print. Any idea, where I am doing wrong...???
From what your describe it looks like that standalone printer is running some kind of "text printing service" on your given port. So looks like everything you send to this port will be printed as text.
Whereas when you have "Shared" printer on your Windows machine, it's implemented using Windows Printer service or smth like that. It's not just simple socket/port anymore where you can write ASCII text.

Categories

Resources