I am trying to print a String through a USB printer.
I use the following method:
public void printMessage(Context context,String msg) {
// TODO Auto-generated method stub
final String printdata = msg;
final UsbEndpoint mEndpointBulkOut;
if (mUsbManager.hasPermission(mDevice)){
UsbInterface intf = mDevice.getInterface(0);
for (int i = 0; i < intf.getEndpointCount(); i++) {
UsbEndpoint ep = intf.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
mEndpointBulkOut = ep;
connection = mUsbManager.openDevice(mDevice);
if(connection!=null)
{
Log.e("Connection:"," connected");
Toast.makeText(context, "Device connected", Toast.LENGTH_SHORT).show();
}
boolean forceClaim = true;
connection.claimInterface(intf, forceClaim );
Integer res = connection.bulkTransfer(mEndpointBulkOut, printdata.getBytes(), printdata.getBytes().length, 10000);
new Thread(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
Log.i("Thread:", "in run thread");
byte[] bytes = printdata.getBytes();
int b = connection.bulkTransfer(mEndpointBulkOut, bytes, bytes.length, 100000);
Log.i("Return Status", "b-->" + b);
}
}).start();
connection.releaseInterface(intf);
break;
}
}
}
}else{
mUsbManager.requestPermission(mDevice, mPermissionIntent);
Toast.makeText(context, "Device have no permission", Toast.LENGTH_SHORT).show();
}
}
The problem here sche mDevice
is null. The method where you supposedly give value to mDevice
is:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
intent = new Intent();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
mDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(mDevice != null){
}
}
else {
Log.d(TAG, "Permiso denegado " + mDevice);
}
}
}
}
};
Thanks. Greetings.