安卓设备连接USB打印机

首先,感谢CSDN这个平台,为广大程序员提供一个相互交流的平台,其次,感谢广大程序员,让我学到了很多。这篇博客的内容也是我归纳了诸多博主的内容。亲测有效。废话少说,直接代码

1,主activity

package dayin.com.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);

        //必须的一步
        USBPrinter.initPrinter(MainActivity.this);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PrinterUtil util = new PrinterUtil(MainActivity.this);
                List<String> line = new ArrayList<String>();


                line.add("名称阿萨德发的啥地方啥地方啥地方啥地方阿斯蒂芬啥地方阿斯蒂芬阿斯蒂芬阿斯蒂芬啥地方");
                line.add("名称"+"\t"+"是否阿斯蒂芬");
//                line.add("1234567890");
//                line.add("abcdefghijklmnopqrstuvwxyz"+"\n");
                
                util.createData(line);


            }
        });
    }
}

 

2,工具类

package dayin.com.myapplication;

import android.content.Context;
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.util.Log;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


public class PrinterUtil {

   private static String TAG = "PrinterUtil";
   private UsbManager usbManager;
   private Context ctx;
   public static final byte LF = 10;
   public static final byte ESC = 27;
   public static final byte GS = 29;
   private UsbDevice myUsbDevice;// 满足的设�??
   private UsbInterface usbInterface;// usb接口
   private UsbEndpoint epControl;// 控制端点
   private UsbDeviceConnection myDeviceConnection;// 连接
   /**
    * 块输出端
    */
   private UsbEndpoint epBulkOut;
   private UsbEndpoint epBulkIn;
   /**
    * 中断端点
    */
   private UsbEndpoint epIntEndpointOut;
   private UsbEndpoint epIntEndpointIn;

   public PrinterUtil(Context ctx) {
      this.ctx = ctx;
   }

   public boolean connect() {
      // 1)创建usbManager
      usbManager = (UsbManager) ctx.getSystemService(Context.USB_SERVICE);
      // 2)获取到所有设�?? 选择出满足的设备
      enumeraterDevices();
      if (usbInterface == null || myUsbDevice == null) {
         return false;
      }
      // 4)获取设备endpoint
      assignEndpoint();
      // 5)打开conn连接通道
      openDevice();

      return true;
   }


   public void createData(List<String> line) {
      ByteBuffer buffer = ByteBuffer.allocate(1024 * 160);
      buffer.put(init_printer());
      buffer.put(print_linefeed());
      buffer.put(print_linefeed());
      buffer.put(print_linefeed());
      buffer.put(print_linefeed());
      for (int i = 0; i < line.size(); i++) {
         try {
            buffer.put((line.get(i) + "\n").getBytes("GBK"));
         } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
         }
      }
      buffer.put(feedpapercut());

      int len = buffer.position();
      byte[] bytes = new byte[len];
      buffer.rewind();
      buffer.get(bytes, 0, len);
      buffer.clear();

      send(bytes);
   }

   public void send(final byte[] buffer) {
      if (!connect()) {
         Log.e(TAG, "连接失败!");
         return;
      }
      new Thread(new Runnable() {
         @Override
         public void run() {
            try {
               sendMessageToPoint(buffer);
            } catch (Exception e) {
            }
         }
      }).start();
   }

   /**
    * 枚举设备
    */
   public void enumeraterDevices() {
      HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
      Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
      while (deviceIterator.hasNext()) {
         UsbDevice device = deviceIterator.next();
         UsbInterface usbinterface = device.getInterface(0);
         if (usbinterface.getInterfaceClass() == 7) {
            myUsbDevice = device;
            usbInterface = usbinterface;
         }
      }
   }

   /**
    * 分配端点,IN | OUT,即输入输出;可以�?�过判断
    */
   private void assignEndpoint() {
      if (usbInterface != null) {
         for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
            UsbEndpoint ep = usbInterface.getEndpoint(i);
            switch (ep.getType()) {
            case UsbConstants.USB_ENDPOINT_XFER_BULK:// �??
               if (UsbConstants.USB_DIR_OUT == ep.getDirection()) {// 输出
                  epBulkOut = ep;
                  System.out.println("Find the BulkEndpointOut," + "index:" + i + "," + "使用端点号:" + epBulkOut.getEndpointNumber());
               } else {
                  epBulkIn = ep;
                  System.out.println("Find the BulkEndpointIn:" + "index:" + i + "," + "使用端点号:" + epBulkIn.getEndpointNumber());
               }
               break;
            case UsbConstants.USB_ENDPOINT_XFER_CONTROL:// 控制
               epControl = ep;
               System.out.println("find the ControlEndPoint:" + "index:" + i + "," + epControl.getEndpointNumber());
               break;
            case UsbConstants.USB_ENDPOINT_XFER_INT:// 中断
               if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {// 输出
                  epIntEndpointOut = ep;
                  System.out.println("find the InterruptEndpointOut:" + "index:" + i + "," + epIntEndpointOut.getEndpointNumber());
               }
               if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                  epIntEndpointIn = ep;
                  System.out.println("find the InterruptEndpointIn:" + "index:" + i + "," + epIntEndpointIn.getEndpointNumber());
               }
               break;
            default:
               break;
            }
         }
      }
   }

   /**
    * 连接设备
    */
   public void openDevice() {
      if (usbInterface != null) {// 接口是否为null
         // 在open前判断是否有连接权限;对于连接权限可以静态分配,也可以动态分配权�??
         UsbDeviceConnection conn = null;
         if (usbManager.hasPermission(myUsbDevice)) {
            // 有权限,那么打开
            conn = usbManager.openDevice(myUsbDevice);
         }
         if (null == conn) {
            Toast.makeText(ctx, "无法连接设备!", Toast.LENGTH_SHORT).show();
            return;
         }
         // 打开设备
         if (conn.claimInterface(usbInterface, true)) {
            myDeviceConnection = conn;
            if (myDeviceConnection != null)// 到此你的android设备已经连上zigbee设备
               System.out.println("打开设备成功!");
            final String mySerial = myDeviceConnection.getSerial();
         } else {
            Toast.makeText(ctx, "打开设备失败!", Toast.LENGTH_SHORT).show();
            conn.close();
         }
      }
   }

   /**
    * 
    * @param buffer
    */
   public void sendMessageToPoint(byte[] buffer) {
      if (myDeviceConnection.bulkTransfer(epBulkOut, buffer, buffer.length, 0) >= 0) {
         // myUsbDevice.
         Toast.makeText(ctx, "send success", Toast.LENGTH_SHORT).show();
      } else {
         Toast.makeText(ctx, "send failed", Toast.LENGTH_SHORT).show();
      }
   }

   /**
    * Print and line feed LF
    * 
    * @return bytes for this command
    */
   public static byte[] print_linefeed() {
      byte[] result = new byte[1];
      result[0] = LF;

      return result;
   }

   /**
    * Initialize printer Clears the data in the print buffer and resets the printer modes to the modes that were in effect when the power was turned on. ESC @
    * 
    * @return bytes for this command
    */
   public byte[] init_printer() {
      byte[] result = new byte[2];
      result[0] = ESC;
      result[1] = 64;
      return result;
   }

   /**
    * feed paper and cut Feeds paper to ( cutting position + n x vertical motion unit ) and executes a full cut ( cuts the paper completely )
    * 
    * @return bytes for this command
    */
   public byte[] feedpapercut() {
      byte[] result = new byte[4];
      result[0] = GS;
      result[1] = 86;
      result[2] = 65;
      result[3] = 0;
      return result;
   }

}

3,打印类

package dayin.com.myapplication;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
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.util.Log;
import android.widget.Toast;

import java.util.HashMap;

/**
 * Created by lake
 * 此类的功能:打印
 */
public class USBPrinter {
    private static final String ACTION_USB_PERMISSION = "com.usb.printer.USB_PERMISSION";

    private static USBPrinter mInstance;

    private Context mContext;
    private UsbDevice mUsbDevice;
    private PendingIntent mPermissionIntent;
    private UsbManager mUsbManager;
    private UsbDeviceConnection mUsbDeviceConnection;

    private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        mUsbDevice = usbDevice;
                    } else {
                        Toast.makeText(context, "设备权限被拒绝 " + usbDevice, Toast.LENGTH_SHORT).show();
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                if (mUsbDevice != null) {
                    Toast.makeText(context, "关闭设备连接!", Toast.LENGTH_SHORT).show();
                    if (mUsbDeviceConnection != null) {
                        mUsbDeviceConnection.close();
                    }
                }
            }
        }
    };


    public static USBPrinter getInstance() {
        if (mInstance == null) {
            mInstance = new USBPrinter();
        }
        return mInstance;
    }

    /**
     * 初始化打印机,需要与destroy对应
     *
     * @param context 上下文
     */
    public static void initPrinter(Context context) {
        getInstance().init(context);
    }

    /**
     * 销毁打印机持有的对象
     */
    public static void destroyPrinter() {
        getInstance().destroy();
    }

    private void init(Context context) {
        mContext = context;
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        mContext.registerReceiver(mUsbDeviceReceiver, filter);

        // 列出所有的USB设备,并且都请求获取USB权限
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();

        for (UsbDevice device : deviceList.values()) {
            mUsbManager.requestPermission(device, mPermissionIntent);
        }
    }

    private void destroy() {
        mContext.unregisterReceiver(mUsbDeviceReceiver);

        if (mUsbDeviceConnection != null) {
            mUsbDeviceConnection.close();
            mUsbDeviceConnection = null;
        }

        mContext = null;
        mUsbManager = null;
    }

    /**
     * 打印方法
     * @param msg
     */
    public void print(String msg) {
        final String printData = msg;
        if (mUsbDevice != null) {
            UsbInterface usbInterface = mUsbDevice.getInterface(0);
            for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
                final UsbEndpoint ep = usbInterface.getEndpoint(i);
                if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                    if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                        mUsbDeviceConnection = mUsbManager.openDevice(mUsbDevice);
                        if (mUsbDeviceConnection != null) {
                            Toast.makeText(mContext, "设备连接!", Toast.LENGTH_SHORT).show();
                            mUsbDeviceConnection.claimInterface(usbInterface, true);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    byte[] bytes = printData.getBytes();
                                    int b = mUsbDeviceConnection.bulkTransfer(ep, bytes, bytes.length, 100000);
                                    Log.i("Return Status", "b-->" + b);
                                }
                            }).start();

                            mUsbDeviceConnection.releaseInterface(usbInterface);
                            break;
                        }
                    }
                }
            }
        } else {
            Toast.makeText(mContext, "没安装USB设备!", Toast.LENGTH_SHORT).show();
        }
    }
}

注意:第一次使用的时候会弹出提示框,允许链接设备的。此时无法打印。需要退出此界面再次进入即可。以后就正常了。只有第一次会这样。

链接:https://download.csdn.net/download/qq_30299243/10998178

ok,开始你的表演吧!!!

布局文件就不写了,一个新项目默认的布局

 

评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值