Android USB打印/蓝牙打印 ESC/POS打印 无依赖其他SDK
程序员文章站
2022-03-21 08:01:50
Android USB打印/蓝牙打印 ESC/POS打印 无依赖其他SDK USB工具类蓝牙工具类ESC/POS指令类打印类使用方法USB工具类新建文件 UsbUtil.java//USB工具类public class UsbUtil{ private static UsbManager mUsbManager; public UsbManager getUsbManager(){ return mUsbManager; } private sta...
Android USB打印/蓝牙打印 ESC/POS打印 无依赖其他SDK
USB工具类
新建文件 UsbUtil.java
//USB工具类
public class UsbUtil{
private static UsbManager mUsbManager;
public UsbManager getUsbManager(){
return mUsbManager;
}
private static final String ACTION_USB_PERMISSION = "com.usb.printer.USB_PERMISSION";
//注册广播
private static final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//广播方法
String action = intent.getAction();
//申请使用USB设备权限回调广播
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
} else {
Toast.makeText(context, "设备的权限被拒绝 " + usbDevice, Toast.LENGTH_SHORT).show();
}
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
}
}
};
//获取USB设备
public static List<UsbDevice> getUsbDeviceList(Context context) {
//获取USB管理器
mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
//注册申请使用USB设备权限回调广播
context.registerReceiver(mUsbDeviceReceiver, filter);
// 列出所有的USB设备,并且都请求获取USB权限
assert mUsbManager != null;
HashMap<String,UsbDevice> deviceList = mUsbManager.getDeviceList();
int index = 0;
ArrayList<UsbDevice> usbDeviceList = new ArrayList<>();
for (UsbDevice device : deviceList.values()) {
if(!mUsbManager.hasPermission(device)){
//申请使用权限
mUsbManager.requestPermission(device, pendingIntent);
}
usbDeviceList.add(device);
}
return usbDeviceList;
}
public static UsbInterface getUsbInterface(UsbDevice device){
UsbInterface usbInterface = null;
for (int i=0;i<device.getInterfaceCount();i++){
usbInterface = device.getInterface(i);
if (usbInterface.getInterfaceClass() != UsbConstants.USB_CLASS_PRINTER) {
usbInterface = null;
}else{
break;
}
}
return usbInterface;
}
//选择打印机
public static UsbEndpoint getUsbEndpoint(UsbInterface usbInterface) {
UsbEndpoint usbEndpoint = null;
for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
UsbEndpoint ep = usbInterface.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
usbEndpoint = ep;
break;
} else {
//这里是输入设备 暂时不管
}
}
}
return usbEndpoint;
}
//打印
public static Boolean print( UsbDevice usbDevice,byte[] bytes){
UsbDeviceConnection connection = mUsbManager.openDevice(usbDevice);
UsbInterface usbInterface = getUsbInterface(usbDevice);
UsbEndpoint usbEndpoint = getUsbEndpoint(usbInterface);
if (connection != null && connection.claimInterface(usbInterface, true)) {
int result = connection.bulkTransfer(usbEndpoint, bytes, bytes.length, 500);
connection.close();
return true;
}
return false;
}
}
蓝牙工具类
新建文件 BluetoothUtil.java
//蓝牙工具类
public class BluetoothUtil {
private static BluetoothSocket mBluetoothSocket= null;
private static OutputStream mOutputStream;
//检测蓝牙是否打开
public static boolean checkBluetoothOn() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null)
// 蓝牙已打开
if (mBluetoothAdapter.isEnabled()){
return true;
}
return false;
}
//请求打开蓝牙
public static void openBluetooth(Activity activity) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(enableBtIntent, 666);
}
//获取所有已配对的设备
public static List<BluetoothDevice> getPairedDevices() {
List deviceList = new ArrayList<>();
Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceList.add(device);
}
}
return deviceList;
}
//获取所有已配对的打印设备
public static List<BluetoothDevice> getPairedPrinterDevices() {
if(checkBluetoothOn()){
return getSpecificDevice(BluetoothClass.Device.Major.IMAGING);
}
return new ArrayList<>();
}
//从已配对设配中,选出某一特定类型的设备展示
public static List<BluetoothDevice> getSpecificDevice(int deviceClass){
List<BluetoothDevice> bluetoothDevices = BluetoothUtil.getPairedDevices();
List<BluetoothDevice> printerDevices = new ArrayList<>();
for (BluetoothDevice device : bluetoothDevices) {
BluetoothClass bluetoothClass = device.getBluetoothClass();
if (bluetoothClass.getMajorDeviceClass() == deviceClass)
printerDevices.add(device);
}
return printerDevices;
}
//连接蓝牙打印设备
public static BluetoothSocket connectDevice(BluetoothDevice device) {
if(mBluetoothSocket!=null){
try {
mBluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
mBluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mBluetoothSocket.connect();
} catch (IOException e) {
try {
assert mBluetoothSocket != null;
mBluetoothSocket.close();
} catch (IOException closeException) {
return null;
}
return null;
}
return mBluetoothSocket;
}
//获取输出流
public static OutputStream getOutputStream(){
try {
//如果之前已经创建 则把之前的关闭掉
if (mOutputStream != null) {
mOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
assert mBluetoothSocket != null;
try {
mOutputStream = mBluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return mOutputStream;
}
//打印
public static Boolean print(OutputStream outputStream, byte[] bytes){
if(outputStream == null){
return false;
}
try {
outputStream.write(bytes);
outputStream.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
ESC/POS指令类
public class EscCommand {
private Vector<Byte> command;
public EscCommand() {
this.command = new Vector<>(4096, 1024);
//添加初始化命令
byte[] bytes = {27,64};
addArrayToCommand(bytes);
}
private void addArrayToCommand(byte[] array) {
for (byte anArray : array) {
this.command.add(anArray);
}
}
private void addStrToCommand(String str) {
byte[] bs = null;
if (!str.equals("")) {
try {
bs = str.getBytes("GB2312");
} catch (UnsupportedEncodingException var4) {
var4.printStackTrace();
}
if (bs != null) {
for (byte b : bs) {
this.command.add(b);
}
}
}
}
//添加文本
public void addText(String text) {
this.addStrToCommand(text);
}
//添加字节集
public void addBytes(byte[] bytes) {
addArrayToCommand(bytes);
}
//0 居左 1居中 2居右
public void addSelectJustification(int just) {
byte[] command = new byte[]{27, 97, (byte) just};
this.addArrayToCommand(command);
}
//获取打印命令
public byte[] getByteArrayCommand() {
return convertToByteArray(this.command);
}
private byte[] convertToByteArray(Vector<Byte> vector) {
if (vector == null || vector.isEmpty())
return new byte[0];
Byte[] bytes = vector.toArray(new Byte[vector.size()]);
return toPrimitive(bytes);
}
private byte[] toPrimitive(Byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return new byte[0];
} else {
byte[] result = new byte[array.length];
for (int i = 0; i < array.length; ++i) {
result[i] = array[i];
}
return result;
}
}
}
打印类
//打印类
public class Printer{
private EscCommand mEsc = null;
public EscCommand getEscCommand() {
return mEsc;
}
//自身静态类
private static Printer mInstance = null;
//线程
private final ExecutorService threadPool;
private Activity mActivity = null;
public void setActivity(Activity activity) {
mActivity = activity;
}
private List<BluetoothDevice> mBluetoothDeviceList = null;
//蓝牙打印设备
BluetoothDevice mBluetoothDevice = null;
public BluetoothDevice getBluetoothDevice() {
return mBluetoothDevice;
}
//打印机连接类
BluetoothSocket mBluetoothSocket;
//打印输出流
OutputStream mOutputStream = null;
public OutputStream getOutputStream() {
return mOutputStream;
}
private List<UsbDevice> mUsbDeviceList = null;
//USB打印设备
UsbDevice mUsbDevice = null;
public UsbDevice getUsbDevice() {
return mUsbDevice;
}
//打印机类型 0USB打印机 1蓝牙打印机
private int mPrintType = 0;
private Printer() {
threadPool = Executors.newFixedThreadPool(1);
}
public static Printer getInstance() {
if (mInstance == null) {
mInstance = new Printer();
}
return mInstance;
}
//获取打印机类型
public int getPrintType() {
return mPrintType;
}
//发送打印命令
public void sendPrintCommand(byte[] bytes) {
SendCommandThread thread = new SendCommandThread(this, bytes);
threadPool.execute(thread);
}
//线程池打印
private class SendCommandThread extends Thread {
private Printer mPrinter;
private byte[] bytes;
public SendCommandThread(Printer printer, byte[] bytes) {
this.mPrinter = printer;
this.bytes = bytes;
}
@Override
public void run() {
super.run();
int printType = mPrinter.getPrintType();
if (printType == 0) {
//USB打印
UsbUtil.print(mUsbDevice, mPrinter.getEscCommand().getByteArrayCommand());
} else if (printType == 1) {
//蓝牙打印
BluetoothUtil.print(mOutputStream, mPrinter.getEscCommand().getByteArrayCommand());
}
/* if (connection != null && connection.claimInterface(usbEscPosPrinter.getUsbInterface(), true)) {
// int sendResultCode = result > 0 ? SendResultCode.SEND_SUCCESS : SendResultCode.SEND_FAILED;
// sendMessage(sendResultCode, usbPrinter.getPrinterName());
}*/
}
}
//获取所有打印设备
public String getPrints() {
StringBuilder prints = new StringBuilder("[");
int index = 0;
mUsbDeviceList = UsbUtil.getUsbDeviceList(mActivity);
for (UsbDevice device : mUsbDeviceList) {
index++;
prints.append("{\"name\":\"USB打印机-").append(index).append("\",\"index\":").append(index).append("},");
}
mBluetoothDeviceList = BluetoothUtil.getPairedPrinterDevices();
for (BluetoothDevice device : mBluetoothDeviceList) {
index++;
prints.append("{\"name\":\"蓝牙打印机-").append(device.getName()).append("\",\"index\":").append(index).append("},");
}
prints = new StringBuilder(prints.substring(0, prints.length() - 1) + "]");
return prints.toString();
}
//选择打印设备
public int optionPrint(int num) {
init();
if (num <= 0) {
return 0;
}
int size = mUsbDeviceList.size();
if (size <= num && size > 0) {
mPrintType = 0;
mUsbDevice = mUsbDeviceList.get(num - 1);
return 1;
} else {
size = mBluetoothDeviceList.size();
num -= mUsbDeviceList.size();
if (size <= num && size > 0) {
mPrintType = 1;
mBluetoothSocket = BluetoothUtil.connectDevice(mBluetoothDeviceList.get(num - 1));
if(mBluetoothSocket==null){
return 0;
}
mOutputStream = BluetoothUtil.getOutputStream();
if(mOutputStream == null){
return 0;
}
return 1;
}
}
return 0;
}
//初始化打印命令
public void init() {
mEsc = new EscCommand();
}
//打印文本
public void print(String message) {
mEsc.addText(message);
}
//打印空白行
public void printBlank() {
byte[] bytes = {27, 33, 0, 10, 13, 10, 13, 10, 13, 10, 13};
mEsc.addBytes(bytes);
}
//打印一行
public void printLine(String content) {
content += "\r\n";
mEsc.addText(content);
}
//设置字体大小
public void setFontSize(int size) {
//size 取值范围 0-7 16-23 32-39 64-71
mEsc.addBytes(new byte[]{29, 33, (byte) size});
}
//设置下划线
public void setFontDownLine(int num) {
byte[] bytes;
if (num == 1) {
bytes = new byte[]{27, 45, 1};
} else if (num == 2) {
bytes = new byte[]{27, 45, 2};
} else {
bytes = new byte[]{27, 45, 0};
}
mEsc.addBytes(bytes);
}
//设置粗体
public void setWeight(Boolean status) {
if (status) {
mEsc.addBytes(new byte[]{27, 69, 1});
} else {
mEsc.addBytes(new byte[]{27, 69, 0});
}
}
//设置对齐方式
public void setAlign(int type) {
mEsc.addSelectJustification(type);
}
//最后调用----输出所有打印命令到设备进行打印
public void PrintAll() {
sendPrintCommand(mEsc.getByteArrayCommand());
}
}
使用方法
//获取打印类
Printer printer = Printer.getInstance();
//设置Activity
printer.setActivity(this);
//获取所有打印机 需自行处理并显示获取到的所有打印机
printer.getPrints();
//选择 getPrints 返回的打印机中的一个
printer.optionPrint(0);
//初始化打印机
printer.init();
//设置居中
printer.setAlign(1);
//设置大号字体
printer.setFontSize(35);
//打印标题
printer.print("这里是标题");
//设置左边对齐
printer.setAlign(0);
//设置默认字体
printer.setFontSize(0);
printer.print("--------------------------------");
printer.print("这里是内容区域");
//打印所有
printer.PrintAll();
本文地址:https://blog.csdn.net/it2299888/article/details/107172388