Java 使用USB OTG打印PDF文件,打印机-Epson L130

Java 使用USB OTG打印PDF文件,打印机-Epson L130,java,android,Java,Android,我可以连接到打印机。m面临的问题是——它正在打印字节数组。请一定要看看代码,在我发送字节数组。我保存了一个pDF文件。很抱歉评论了这些试用版。先谢谢你。感谢您的帮助。 包com.net.atos.printusb import android.annotation.TargetApi; import android.app.PendingIntent;

我可以连接到打印机。m面临的问题是——它正在打印字节数组。请一定要看看代码,在我发送字节数组。我保存了一个pDF文件。很抱歉评论了这些试用版。先谢谢你。感谢您的帮助。 包com.net.atos.printusb

                            import android.annotation.TargetApi;
                            import android.app.PendingIntent;
                            import android.content.BroadcastReceiver;
                            import android.content.Context;
                            import android.content.ContextWrapper;
                            import android.content.Intent;
                            import android.content.IntentFilter;
                            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.net.Uri;
                            import android.os.Build;
                            import android.os.Handler;
                            import android.os.Message;
                            import android.support.v7.app.AppCompatActivity;
                            import android.os.Bundle;
                            import android.util.Base64;
                            import android.util.Log;
                            import android.view.View;
                            import android.widget.Button;
                            import android.widget.EditText;
                            import android.widget.Toast;
                            import java.io.BufferedOutputStream;
                            import java.io.File;
                            import java.io.FileInputStream;
                            import java.io.FileOutputStream;
                            import java.nio.ByteBuffer;
                            import java.util.HashMap;
                            import java.util.Iterator;

                                        public class PrintMessage extends AppCompatActivity {
                                            private final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
                                            Button create_file;
                                            PendingIntent mPermissionIntent;
                                            UsbManager usbManager;
                                            UsbDevice device;
                                             EditText print_text;
                                            UsbDevice printer = null;
                                            private static final int PRINTER_VENDOR_ID_1 = 1208;
                                            private static final int PRINTER_VENDOR_ID_2 = 5401;
                                            private BufferedOutputStream mOutputStream;






                                                @Override
                                                protected void onCreate(Bundle savedInstanceState)
                                                {
                                                    super.onCreate(savedInstanceState);
                                                        setContentView(R.layout.activity_print_message);

                                                    try{


                                                        print_text = (EditText)findViewById(R.id.edt_print);

                                                        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
                                                        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();

                                                        if (deviceList.size() <= 0)
                                                        {
                                                            Toast.makeText(getApplicationContext(), "Info: No device found", Toast.LENGTH_SHORT).show();
                                                        }
                                                        else
                                                        {
                                                            Toast.makeText(getApplicationContext(), "No of devices " + deviceList.size(), Toast.LENGTH_SHORT).show();
                                                           /* ((TextView) findViewById(R.id.textView_devices))
                                                                    .setText("No of device : " + deviceList.size());*/
                                                        }
                                                        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
                                                        int count = 0;
                                                        mPermissionIntent = PendingIntent.getBroadcast(getBaseContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);

                                                        while (deviceIterator.hasNext())
                                                        {

                                                            count++;
                                                            device = deviceIterator.next();
                                                            Toast.makeText(PrintMessage.this, " vendor id " + device.getVendorId(), Toast.LENGTH_LONG).show();
                                                            Toast.makeText(PrintMessage.this, " prod id " + device.getProductId(), Toast.LENGTH_LONG).show();
                                                            Toast.makeText(PrintMessage.this, " device name " + device.getDeviceName(), Toast.LENGTH_LONG).show();
                                                            if (device.getVendorId() == PRINTER_VENDOR_ID_1  || device.getVendorId() == PRINTER_VENDOR_ID_2 ) {
                                                                printer = device;
                                                                break;
                                                            }

                                                        }


                                                        findViewById(R.id.btn_print).setOnClickListener(new View.OnClickListener() {
                                                            @Override
                                                            public void onClick(View v) {



                                                                if (print_text.getText().toString().length() > 0) {
                                                                    Log.i("Info", "Print command given");
                                                                    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                                                                    registerReceiver(mUsbReceiver, filter);
                                                                    Toast.makeText(PrintMessage.this, "register receiver called ", Toast.LENGTH_LONG).show();

                                                                    if (printer != null) {
                                                                        usbManager.requestPermission(printer, mPermissionIntent);
                                                                        Toast.makeText(PrintMessage.this, "Printer found- request permission ", Toast.LENGTH_LONG).show();
                                                                    } else {
                                                                        Toast.makeText(PrintMessage.this, "Printer not found", Toast.LENGTH_LONG).show();
                                                                        Log.e("Exception", "Printer not found");
                                                                    }
                                                                }  else
                                                                    {
                                                                        Toast.makeText(PrintMessage.this, "Please write something to print", Toast.LENGTH_SHORT).show();
                                                                    }


                                                                }

                                                                });

                                                    } catch (Exception e) {
                                                        Log.e("Exception", "Exception in onCreate " + e.getMessage());
                                                        Toast.makeText(PrintMessage.this, " Exception in onCreate "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                                        e.printStackTrace();
                                                    }

                                                }

                                                private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
                                                {
                                                    @Override
                                                    public void onReceive(Context context, Intent intent)
                                                    {
                                                        try {
                                                            String action = intent.getAction();
                                                            if (ACTION_USB_PERMISSION.equals(action))
                                                            {
                                                                synchronized (this)
                                                                {
                                                                    final UsbDevice printerDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                                                                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
                                                                    {
                                                                        if (printerDevice != null) {

                                                                            Log.i("Info", "Device permission granted");
                                                                            startPrinting(printerDevice);
                                                                            Toast.makeText(PrintMessage.this, "start printing method called", Toast.LENGTH_SHORT).show();

                                                                        }else{

                                                                            Toast.makeText(PrintMessage.this, "printerDevice is null", Toast.LENGTH_SHORT).show();
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        Log.d("Debug", "permission denied for device "
                                                                                + printerDevice);
                                                                    }
                                                                }
                                                            }
                                                        } catch (Exception e)
                                                        {
                                                            Toast.makeText(PrintMessage.this, "in receiver "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                                            Log.e("Exception", "Exception in onRecieve " + e.getMessage());
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                };




                                                public void startPrinting(final UsbDevice printerDevice)
                                                {
                                                    new Handler().post(new Runnable()
                                                    {
                                                        UsbDeviceConnection conn;
                                                        UsbInterface usbInterface;


                                                        byte[] byteArray;
                                                        @TargetApi(Build.VERSION_CODES.KITKAT)
                                                        @Override
                                                        public void run()
                                                        {
                                                            try
                                                            {
                                                                Log.i("Info", "Bulk transfer started");
                                                                usbInterface = printerDevice.getInterface(0);



                                                                UsbEndpoint   endPoint = usbInterface.getEndpoint(1);
                                                                conn = usbManager.openDevice(printer);
                                                                conn.claimInterface(usbInterface, true);



                                                                //file init
                                                                File pdfFile = new File("/storage/emulated/0/sample/sample.pdf");
                                                                byte[] byteArray = new byte[(int) pdfFile.length()];
                                                                FileInputStream fis = new FileInputStream(pdfFile);
                                                                fis.read(byteArray);
                                                               // fis.close();

                                                                fis.close();

                                                                Toast.makeText(PrintMessage.this, "driver spson ", Toast.LENGTH_SHORT).show();



                                                                ByteBuffer output_buffer = ByteBuffer.allocate(byteArray.length);
                                                                UsbRequest request = new UsbRequest();
                                                                request.initialize(conn, endPoint);
                                                                request.queue(output_buffer, byteArray.length);

                                                                Toast.makeText(PrintMessage.this, " "+byteArray.toString().length(), Toast.LENGTH_SHORT).show();

                                                                if (conn.requestWait() == request)
                                                                {
                                                                    Log.i("Info", output_buffer.getChar(0) + "");
                                                                    Message m = new Message();
                                                                    m.obj = output_buffer.array();
                                                                    Toast.makeText(PrintMessage.this, "in if condition " , Toast.LENGTH_SHORT).show();

                                                                    // handler.sendMessage(m);
                                                                    output_buffer.clear();

                                                                }
                                                                else
                                                                {
                                                                    Log.i("Info", "No request recieved");
                                                                    Toast.makeText(PrintMessage.this, "No request recieved" , Toast.LENGTH_SHORT).show();

                                                                }

                                                               // File file = new File("/storage/emulated/0/sample/sample.pdf");
                                                              //  String string = "\nThis \nis \nmy \nsample \ntext";
                                                                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/storage/emulated/0/sample/sample.pdf"));
                                                                bos.write(byteArray);
                                                                bos.flush();
                                                                bos.close();

                                                                int transfered = conn.bulkTransfer(endPoint, byteArray /*encoded.getBytes()*/ /*byteArray*/, byteArray/*encoded.getBytes()*//*byteArray*/.length, 5000);

                                                                Log.i("Info", "Amount of data transferred : " +transfered);
                                                                Toast.makeText(PrintMessage.this, "bulk transfer "  +transfered , Toast.LENGTH_SHORT).show();

                                                            } catch (Exception e)
                                                            {
                                                                Toast.makeText(PrintMessage.this, " in startPrinting " + e.getMessage(), Toast.LENGTH_SHORT).show();
                                                                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");
                                                                    Toast.makeText(PrintMessage.this, "in finally block  " , Toast.LENGTH_SHORT).show();
                                                                }
                                                                catch (Exception e)
                                                                {
                                                                    Toast.makeText(PrintMessage.this, "startprinting finally " + e.getMessage(), Toast.LENGTH_SHORT).show();
                                                                    Log.e("Exception", "Unable to release resources because : " + e.getMessage());
                                                                    e.printStackTrace();

                                                                }
                                                            }
                                                        }
                                                    });
                                                }


                                            }
导入android.annotation.TargetApi;
导入android.app.pendingent;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.ContextWrapper;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.hardware.usb.UsbConstants;
导入android.hardware.usb.UsbDevice;
导入android.hardware.usb.UsbDeviceConnection;
导入android.hardware.usb.UsbEndpoint;
导入android.hardware.usb.usb接口;
导入android.hardware.usb.UsbManager;
导入android.hardware.usb.UsbRequest;
导入android.net.Uri;
导入android.os.Build;
导入android.os.Handler;
导入android.os.Message;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.util.Base64;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Toast;
导入java.io.BufferedOutputStream;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.nio.ByteBuffer;
导入java.util.HashMap;
导入java.util.Iterator;
公共类PrintMessage扩展了AppCompative活动{
私有最终字符串操作\u USB\u PERMISSION=“com.android.example.USB\u PERMISSION”;
按钮创建_文件;
悬而未决的犯罪意图;
UsbManager UsbManager;
USB设备;
编辑文本打印文本;
USB设备打印机=空;
专用静态最终整型打印机\u供应商\u ID\u 1=1208;
专用静态最终整型打印机\u供应商\u ID\u 2=5401;
私有缓冲输出流mOutputStream;
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u print\u message);
试一试{
print_text=(EditText)findViewById(R.id.edt_print);
usbManager=(usbManager)getSystemService(Context.USB_服务);
HashMap deviceList=usbManager.getDeviceList();
if(deviceList.size()0){
Log.i(“信息”,“给出打印命令”);
IntentFilter筛选器=新建IntentFilter(操作\u USB\u权限);
寄存器接收器(mUsbReceiver,过滤器);
Toast.makeText(PrintMessage.this,“注册接收器调用”,Toast.LENGTH_LONG.show();
如果(打印机!=null){
usbManager.requestPermission(打印机、mPermissionIntent);
Toast.makeText(PrintMessage.this,“找到打印机-请求权限”,Toast.LENGTH_LONG.show();
}否则{
Toast.makeText(PrintMessage.this,“未找到打印机”,Toast.LENGTH_LONG.show();
Log.e(“异常”,“未找到打印机”);
}
}否则
{
Toast.makeText(PrintMessage.this,“请写些东西打印”,Toast.LENGTH_SHORT.show();
}
}