安卓设备连接USB打印机

news/2024/10/18 8:24:50/

首先,感谢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;@Overrideprotected 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() {@Overridepublic 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)创建usbManagerusbManager = (UsbManager) ctx.getSystemService(Context.USB_SERVICE);// 2)获取到所有设�?? 选择出满足的设备enumeraterDevices();if (usbInterface == null || myUsbDevice == null) {return false;}// 4)获取设备endpointassignEndpoint();// 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() {@Overridepublic 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() {@Overridepublic 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,开始你的表演吧!!!

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

 


http://www.ppmy.cn/news/338921.html

相关文章

打印机模拟器下载

1、去苹果开发者中心下载&#xff0c;下载里面的Hardware IO Tools。 https://developer.apple.com/downloads 2、运行工具包里的Printer Simulator 3、此时模拟器和手机一样可以实现打印了。

安卓开发中wifi连接打印机打印图片

1.手机连接上打印机的wifi后 public void print(final IWebview iWebview, JSONArray array) { this.mIWebview iWebview; this.activity iWebview.getActivity(); this.mContext iWebview.getContext(); this.mCallBackID array.optStri…

Android 使用第三方软件PrinterShare实现USB 或WIFI 打印功能

想要调用第三方软件首先必须知道intent 这里使用逆向工具获取清单文件的IntentFilter PrinterShare 清单 <activity android:configChanges"keyboardHidden|locale|orientation|screenSize" android:icon"drawable/icon_title" android:name"com.…

cxGrid自动保存当前单元格输入的数据

遇到的问题&#xff0c;利用cxGrid做数据录入界面&#xff0c;当用户在一个单元格中录入数据&#xff0c;没有回车&#xff0c;然后直接点工具条上的保存按钮&#xff0c;执行数据提交&#xff0c;结果当前输入的内容丢掉了&#xff0c;又回到输入前的值。 在群中求助&#xf…

优友机器人价格_优友U05类人型机器人 换汤不换药

在过去机器人听起来似乎和现在的社会太遥远&#xff0c;但是随着科技的进步&#xff0c;机器人已不再是那么神秘了。尽管现在的机器人层出不穷&#xff0c;但功能单一&#xff0c;没有多大的创新&#xff0c;只不过是换汤不换药。和电影里的机器人相差甚远。 北京时间11月24号&…

欢颜机器人价格_好口碑的欢颜机器人现货,欢颜机器人厂家报价

好口碑的欢颜机器人现货 欢颜机器人焊接机器人的使用不仅可以稳定和提高焊接质量&#xff0c;提高生产效率&#xff0c;而且还降低了对工人焊接技术的要求&#xff0c;从而缩短了产品升级的准备周期&#xff0c;减少了相应的设备投资。选择自动生产线结构相匹配、适合的焊接机器…

电销机器人价格_电话电销机器人价格如何?会很贵吗?

如今人工智能非常流行&#xff0c;越来越多的产品被打上智能标签以提高价格。因此&#xff0c;当人们听到“智能”这个词时&#xff0c;他们会第一时间就会想到价格一定很贵吧&#xff01;那么电话电销机器人价格如何?会很贵吗&#xff1f;在这里就由深圳易网行电销机器人的小…

机器人杆长标定_机器人校准系统

机器人校准系统 AutoCal 在线机器人校准方案 专为快速自动确保机器人设备性能。适用于不同机器人应用&#xff0c;与大多数机器人类型兼容。能够检测机器人 结构的偏移或瞬间变化&#xff0c;然后自动更正错误。不浪费宝贵时间且质量保证。 主要是用于机器人中心点复位。完全在…