How to connect a network printer over Android? - android

I want to code an Android app, which will connect to a network printer with a specific IP address, and then make a printing.
For printing I know that I need to write my own Postscript for specific files types, and connecting to a network is not a problem over WIFI.
How to connect to the network printer?

Any device connected to a network will communicate via their IP and Ports / sockets. The simplest way to connect via telnet or socket and write the data to their socket buffers.
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();
}

You might be able to use lpdspooler, that is, if the printer supports LPR/LPD. If you can give some more details about the environment (printer, etc), I might be able to give more information.

Just Add This Code After oncreate Method
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Star has an Android SDK which has port discovery. It'll find any of their wifi receipt printers on your network. http://starmicronics.com/support/SDKDocumentation.aspx

Try to use PrintManager: https://developer.android.com/training/printing/custom-docs
private void doPrint() {
// Get a PrintManager instance
PrintManager printManager = (PrintManager) getActivity()
.getSystemService(Context.PRINT_SERVICE);
// Set job name, which will be displayed in the print queue
String jobName = getActivity().getString(R.string.app_name) + " Document";
// Start a print job, passing in a PrintDocumentAdapter implementation
// to handle the generation of a print document
printManager.print(jobName, new MyPrintDocumentAdapter(getActivity()),
null); //
}

My solution. I used Epson TM series. I think the port is 9100 for default.
In Manifest add:
<uses-permission android:name="android.permission.INTERNET"/>
in the activity use a Thread otherwise u you can the android.os.NetworkOnMainThreadException error.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Socket sock = new Socket("192.168.1.168", 9100);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.println("Hi, test from Android Device");
oStream.println("\n");
oStream.close();
sock.close();
} catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}});
If not enough, add in manifest these:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Well, you cant connect any devices directly as you will need the driver installed. there are 3rd party apps like Google Cloud print that works seamlessly with Android though.

Related

Android 4.2 - Printing using network printer

I need a print a receipt from a receipt printer(network printer) via my android application which is developed by 4.2 version.
is Android 4.2 support printing from the network printer?
can any one please point me to a correct tutorial.
Thanks
device connected to a network will communicate via their IP and Ports / sockets.
try
{
Socket sock = new Socket("IP", port);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.println("");
oStream.println("");
oStream.close();
sock.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
how to print :
private void doPrint() {
PrintManager printManager = (PrintManager) getActivity().getSystemService(Context.PRINT_SERVICE);
printManager.print("My document", new CustomPrintDocumentAdapter(getActivity()), null);
}
where CustomPrintDocumentAdapter extendsPrintDocumentAdapter
and more info about prnting Android Devlprs
more details Refer.

Can't connect to a computer on network running a server in java from my app

I am trying to connect a simple android client to a simple java server on another computer running on the same wi-fi network, i was able to connect with a java code(non android) on eclipse, and the server works just fine, but when i take the same code and put in my android app (android studio), it throws an IOException.
As of right now my protocol just returns a string "yay" and i just want to display it in a View.
My code:
private void createCom2(TextView showResult){
Socket pazeSocket = null;
PrintWriter pw = null;
BufferedReader br = null;
String ip = "10.0.0.4";
try {
pazeSocket = new Socket(ip, 4444);
pw = new PrintWriter(pazeSocket.getOutputStream());
br = new BufferedReader(new InputStreamReader(pazeSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(this,"Don't know about host: " + ip , Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this,"Couldn't get I/O for the connection to: " + ip , Toast.LENGTH_SHORT).show();
}
}
Thanks.
You need Internet permission for your app. Add this line to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
and read more abut permissions here, if you like:
http://developer.android.com/guide/topics/manifest/manifest-intro.html

Connecting Bluetooth in Android

I have done a simple app to connect my phone with an Arduino via BT and all goes right. My phone have Android 2.3.6... But, when I try the app on my tablet (with android 4.0.3), I can't connect. I post here the specific piece of code:
try {
BluetoothSocket socket = mydevice.createRfcommSocketToServiceRecord(UUID.fromString(ARDUINO_STANDAR_UUID));
socket.connect();
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
Log.d(TAG, "Connected");
}
catch (IOException e) { Log.e(TAG, e.getMessage()); }
}
Using the Log, the problem is at socket.connect(); at that point, I have to enter the PIN of the device, but it don't connect anyway... The error is "Connection refused"...
What can be wrong?
Try something like this to take care of the connection. I just updated an old android-10 app the other day to android-17 and dealt with exactly this.
BluetoothDevice yourDevice;
try {
Method m = yourDevice.getClass().getMethod( "createInsecureRfcommSocket", new Class[] { int.class } );
selectedDeviceSocket = (BluetoothSocket) m.invoke( yourDevice, Integer.valueOf( 1 ) );
selectedDeviceSocket.connect();
}

Android Serversocket does not seem to accept connections on emulators

I've been trying to implement a simple socket communication between two Android emulators but just can't seem to get it.
My server:
public void run() {
if (SERVERIP != null) {
try {
serverStatus.setText("My IP: " + SERVERIP);
serverSocket = new ServerSocket(6798);
serverStatus.setText("ServerSocket Created");
}
catch(Exception e) {
e.printStackTrace();
}
try {
while (true) {
serverStatus.setText("waiting for client");
Socket client = serverSocket.accept();
serverStatus.setText("Connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = in.readLine();
serverStatus.setText(line);
in.close();
client.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
else
serverStatus.setText("Couldn't detect internet connection.");
}
My Client:
try {
InetAddress ina = InetAddress.getByName("10.0.2.2");
socket = new Socket(ina, 6789);
}
catch (Exception e) {
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Hey Server!");
dispText.setText("sent");
}
catch (Exception e) {
e.printStackTrace();
}
The Client side goes on to display the message "sent" however the Server does not move beyond "waiting for client" (stuck on the blocking accept()).
I've used telnet on my Windows machine to redirect port 6789 to 6798 on the server emulator's console. I've also tried turning off my firewall and the other suggestions posted on the similar questions asked here. Please help as just can't seem to get it and feel like I'm making a very stupid mistake.
Also, can anyone please tell me how it is possible for the Client to move beyond the Socket creation code line if the Server is still stuck on accept(). Or, does it not matter to the client that the Server isn't responding as long as it is listening on the port??
Android emulators are placed behind a virtual firewall/router by design, and cannot see each other, even when they are on the same network. The "Using Network Redirection", as well as "Interconnecting Emulator Instances" part of Google's doc on the emulator explains how to communicate with an emulator instance.
As for your last question. Use the empty constructor for socket, and then use the connect call with a specified timeout.

wifi printing in android

I want to print file using wifi printing in my android application.I have scanned wifi printer and i am having wifi printer IP address . Now how can i transfer file from android phone to printer to print it ? I am using following code to transfer file to printer `public void uploadFile(File fileName){
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST,21);
client.login(FTP_USER, FTP_PASS);
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory("/");
client.upload(fileName, new MyTransferListener());
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}`
Can anybody help me ? Thanks in advance.
Using Socket you can print from android using network printer in WIFI Connection
Socket objSocket = new Socket();
String sIP = "192.168.1.10"
String sPort = "9100"
InetSocketAddress objEndPoint = new InetSocketAddress(sIP, Integer.parseInt(sPort));
DataOutputStream objOutputStream;
objSocket.connect(objEndPoint, 3000);
objOutputStream = new DataOutputStream(objSocket.getOutputStream());
objOutputStream.write(("Test Print").getBytes());
objOutputStream.close();
objSocket.close();
I think you can might do it without sending whole file, just pick the Strings from the file and make connection with the wifi device, send the text to the device, it will print it. I have done same thing with the bluetooth printer.

Categories

Resources