I have problem.
i have one bluethoot printer adapter "Bluetake BT220" and one printer "Star DP8340S".
i want connect my bluetot bt220 to my app android , i have others connections to zebra printers but implemented the connection.
for this adapter bluethoot, have not connection, looking much the net, I saw that I can connect directly bluethoot.
I can connect to the device but I'm not able to print in the
someone could tell me where I can start?any suggestion is welcome.
any documentation, do not hesitate to ask
thank you all, by make life easier.
I answer to myself.
solved : I've just created a Connection bluethoot follows
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetakebt220 = bluetoothAdapter.getRemoteDevice(obj.getMac().toString());
Method m;
BluetoothSocket mBTsocket= null;
m = bluetakebt220.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
// mBTsocket = (BluetoothSocket) m.invoke(bluetakebt220, 1);
UUID num = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mBTsocket = bluetakebt220.createRfcommSocketToServiceRecord(num);
mBTsocket.connect();
and now just need to print
String txt ="LINE 1 \n LINE 2 \n";
byte[] CPCLFormat = null;
try {
CPCLFormat = txt .getBytes("utf-8");
try {
os.write(CPCLFormat);
} catch (Exception e) {
os.close();
e.printStackTrace();
}
} catch (UnsupportedEncodingException e1) {
CPCLFormat = null;
os.close();
e1.printStackTrace();
}
os.close();
I hope that helps, thanks
Related
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();
}
I am writing an application which sends data to bluetooth printer. Can anyone help me ? how can I use android Bluetooth Stack for printing? or is there any external api or sdk to use?
Here is my code for searching bluetooth...
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 for sending data to 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() , data is not getting print to printer as socket connection getting closed before printing data..and if I didn't write socket.close() then data is getting printed only once.. I would not be able to print data second time until I restart bluetooth of my phone.
can any one have solution for it??? or is there any other way to get rid of this printing??
I got the solution of my problem...
if i want to print data more than one time then you dont need to create new Socket Connection with the device... instead call outputstream.write(bytes) method.
and in the end if you want to disconnect device then call mBTScoket.close() method to disconnect device.
You can use printooth library for any printer, printooth is simple and well documented,
https://github.com/mazenrashed/Printooth
var printables = ArrayList<Printable>()
var printable = Printable.PrintableBuilder()
.setText("Hello World") //The text you want to print
.setAlignment(DefaultPrinter.ALLIGMENT_CENTER)
.setEmphasizedMode(DefaultPrinter.EMPHASISED_MODE_BOLD) //Bold or normal
.setFontSize(DefaultPrinter.FONT_SIZE_NORMAL)
.setUnderlined(DefaultPrinter.UNDELINED_MODE_ON) // Underline on/off
.setCharacterCode(DefaultPrinter.CHARACTER_CODE_USA_CP437) // Character code to support languages
.setLineSpacing(DefaultPrinter.LINE_SPACING_60)
.setNewLinesAfter(1) // To provide n lines after sentence
.build()
printables.add(printable)
BluetoothPrinter.printer().print(printables)
If you have made connection to the devices and paired it.
So for printing, printer wants the byte. SO I have createed a mothod.
Simply call this method and pass the String inside it to get printed.
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;
}
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.
I'm designin an application in Android that connects the mobile to a bluetooth device. I can do this, as I open a BluetoothSocket like this:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
Where device is the paired device with the mobile bluetooth desired. The thing is, this external device is a bit special, and it has different times for writing and answering to the mobile, so I need to put some timeouts on my socket for reading and writing, but I've searched a lot and it seems like BluetoothSocket doesn't support this.
Can anybody tell me a different way to admin timeouts on reading and writing to the port on the BluetoothSocket class for Android?
Thank you!
There are many Exceptions a socket or it's streams can throw. The socket.connect() for example can throw a ConnectTimeoutException. Every method in the BluetoothSocket context can through an IOException just take a look at the documentation and you will see which exception you have to catch in order to make your program work properly.
Here is the code for reading and writing code:
Writng code on port:
try
{
// Enviamos los bytes
DataOutputStream dOut = null;
dOut = new DataOutputStream(socket.getOutputStream());
// Send message
dOut.writeBytes(res);
dOut.flush();
}
catch (IOException e)
{
Dialogs.showErrorDialog("Error al recuperar la fecha y hora del dispositivo Nonin.", this);
}
Then, reading from port until response available:
DataInputStream dIn = null;
// We receive the answer
try
{
dIn = new DataInputStream(socket.getInputStream());
}
catch (IOException e)
{
Dialogs.showAlertDialog("An exception occured during bluetooth io stream creation", this);
}
while (true)
{
try
{
String data = dIn.readLine(); // readLine();
byte[] total = EncodingUtils.getBytes(data, "ASCII");
Dialogs.showInfoDialog("Mensaje ok: " + data.toString(), this);
}
catch (IOException e)
{
break;
}
}
The thing is that I think the writing works, as I convert the desired string into bytes, and it works. But then, when I'm waiting for response, it mixes further responses with the desired, and I think this is because timings.
There's no more code in the middle related with sockets. First, I create it. Then, I try to send a byte String. Then I wait until I receive the answer for the byte String that I just sent.
Thank you in advance.
I have two Android devices which I want to connect, using Bluetooth, and transfer data over an RFCOMM channel. I only one one device to receive data, while the other device sends it...
Using this code, I am able to connect to the other device and begin listening to an RFCOMM channel:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(device, 2);
socket.connect();
class BasicThread implements Runnable{
public void run() {
try {
InputStream stream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
while (true){
Log.d("myapp", "now listening...");
latestLine = r.readLine();
Log.d("myapp", latestLine);
}
} catch (IOException e) {
}
}
}
new Thread(new BasicThread()).run();
Using the other device, I have implemented a listening socket like this:
Method m = blue.getClass().getMethod("listenUsingRfcommOn", new Class[] { int.class });
BluetoothServerSocket socket = (BluetoothServerSocket) m.invoke(blue, 2);
BluetoothSocket sock = socket.accept();
Log.d("myapp", "Connected...\n\n\n\n\n\n\n\n");
OutputStream s = sock.getOutputStream();
final PrintWriter out = new PrintWriter(s);
They both connect on RFCOMM channel 2, and both SEE eachother, however, the second device always remains blocked at the BluetoothSocket sock = socket.accept();
Any help?
OK, I am newbie, but I can try to help. So here is my experience, I managed to connect two devices using reflection. My Android phone is receiving data using method listenUsingInsecureRfcommOn, while other devices are masters in communication and send the data over BT SPP. I had a problem with this method since it makes no visible SDP record, so I could not detect it with other devices. Because of that, I made small sniffer using Bluecove and Java SE that tries to connect to every port in given range. Here's the code:
package application.test;
import static java.lang.System.out;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class RfCommClient {
public static void main(String args[]) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
String add = "btspp://8C71F894A36D:";
String par = ";authenticate=false;encrypt=false;master=true";
String url = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd;HH-mm-ss-SSS");
for (int i = 1; i < 15; ++i) {
try {
url = add + i + par;
out.format("Time: %s, port = %d\n", sdf.format(System.currentTimeMillis()), i);
StreamConnection conn = (StreamConnection) Connector.open(url);
PrintStream ops = new PrintStream(conn.openOutputStream());
ops.println("Hi there...");
// response
Thread.sleep(1000);
InputStream is = conn.openInputStream();
byte[] resp = new byte[5];
int r = is.read(resp);
out.println("r = " + r + ", response = " + new String(resp, "US-ASCII"));
Thread.sleep(10 * 1000);
conn.close();
} catch (Exception e) {
out.println("Exception occured, time = " + sdf.format(System.currentTimeMillis()) + ", i = " + i);
//e.printStackTrace();
}
}
}
}
What I've learned it that some ports are taken, and that some ports can not be uses (as documentation says, e.g. port 0). For example, port 2 I believe was taken, because when I send some data to it I receive 5 chars back beginning with ERR :).
While, on the other hand, my thread is still waiting?! :)
That leads us to another thing I noticed, ports (or channels) are not always mapped to desired number. For example, to me often happened that I want to send something on port 15, but on Android, thread waiting on port 9 received the data :)
So I suggest, check which port is really allocated!
You can achieve that using the code I posted.
And another thing, here is a link to channelPicker function, which selects channel when ordinary API is used, if I am not mistaken, inside some constants should represent reserved channels.
I just noticed something, my code for registering port is slightly different, here is how I do it:
Method m = cba.getDeclaredMethod("listenUsingInsecureRfcommOn", int.class);
ss = (BluetoothServerSocket) m.invoke(BluetoothAdapter.getDefaultAdapter(), port);
Anyway, I know that this is probably too late, but, maybe someone in future has similar question.