Enviar um texto para uma porta USB

144 views
Skip to first unread message

Tiago Grillo

unread,
Jan 12, 2016, 1:50:43 PM1/12/16
to Lista Android
Ola,


    Pessoal preciso enviar um texto pra uma impressora via usb.

    Até vi sobre o USB Host e tal, mas achei uns exemplos muito louco na net, eu não queria listener nada... só abrir usb que vou falar qual, enviar o comando e fechar..

    Preciso de toda a "parafernalha" que encontrei mesmo (UsbController...)


obrigado

claudsan

unread,
Jan 20, 2016, 7:17:17 AM1/20/16
to Android Brasil - Dev

Estudei uma vez algo parecido, na época apenas para estudo utilizei essa lib https://github.com/mik3y/usb-serial-for-android eu testei em um Galaxy TAB.

Tiago Grillo

unread,
Jan 20, 2016, 1:55:47 PM1/20/16
to Lista Android
cara consegui fazer. foi assim

package com.dimep.satjni;

import java.nio.ByteBuffer;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class Impressora {

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private UsbManager manager;
private UsbDevice device;
public Impressora(Context ctx, int venderId) {
manager = (UsbManager) ctx.getSystemService(ctx.USB_SERVICE);
for (UsbDevice dev : manager.getDeviceList().values()) {
if ((dev != null) && (dev.getVendorId() == venderId)) {
device = dev;
}
}
}
public boolean obterPermissao(Context ctx) {
if (manager.hasPermission(device)) {
return true;
} else {
PendingIntent pi = PendingIntent.getBroadcast(
ctx, 0, new Intent(
ACTION_USB_PERMISSION), 0);
manager.requestPermission(device, pi);
return false;
}
}
public void startPrinting(Context ctx, final String texto) throws Exception {
if (device == null)
throw new Exception("Nenhum dispositivo associado.");
obterPermissao(ctx);
Handler handler = new Handler();
handler.post(new Runnable() {
UsbDeviceConnection conn;
UsbInterface usbInterface;

@Override
public void run() {
try {
Log.i("Info", "Bulk transfer started");
// usbInterface = printerDevice.getInterface(0);

for (int i = 0; i < device.getInterfaceCount(); i++) {
usbInterface = device.getInterface(i);

if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_PRINTER) {
// usbInterface = mDevice;
}
}

UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = manager.openDevice(device);
conn.claimInterface(usbInterface, true);

String myStringData = (char)27 + "" + (char)33 + "" + (char)16;
myStringData += "Teste de Impressao";
myStringData += "\n";
myStringData += (char)27 + "" + (char)33 + "" + (char)0;
myStringData += "Codigo: " + texto;
myStringData += "\n";
myStringData += "\n";
myStringData += "\n";
myStringData += (char)29 + "" + (char)86 + "" + (char)0;
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request) {
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
output_buffer.clear();
} else {
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint,
myStringData.getBytes(),
myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " + transfered);

} catch (Exception e) {
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally {
try {
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
// unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
} catch (Exception e) {
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
}


--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Geronildo Jr.

unread,
Feb 3, 2016, 1:26:22 PM2/3/16
to Android Brasil - Dev
Oi Tiago, boa tarde! 

Qual impressora você usou para testar o código?

Tiago Grillo

unread,
Feb 10, 2016, 7:52:12 AM2/10/16
to Lista Android
Ola Geronildo, desculpe a demora, estava de férias..kkk

Então foi com uma Elgin

On Wed, Feb 3, 2016 at 4:26 PM, Geronildo Jr. <geron...@gmail.com> wrote:
Oi Tiago, boa tarde! 

Qual impressora você usou para testar o código?

--

Tiago Grillo

unread,
Feb 10, 2016, 7:54:37 AM2/10/16
to Lista Android
Detalhe, com um tablet Samsung foi de boa só com este código, mas com um Xing Ling que tenho aqui tive que fazer root no aparelho e colocar um arquivo de permissão de USB numa pasta maluca (e especifica) do linux (android) lá para funcionar.

Se precisar deste segundo passo me fale que caço aqui onde exatamente foi.. que não lembro mais de cabeça.
Reply all
Reply to author
Forward
0 new messages