项目地址:点击打开链接

基本思路:

1.创建usbManager;

2.获取到所有设备 选择出满足的设备;

3.查找设备接口;

4.获取设备endpoint;

5.打开conn连接通道;

6.发送打印信息。

注意点:

1.USB权限,在AndroidManifest.xml中添加:

<uses-feature android:name="android.hardware.usb.host" >
</uses-feature>
<uses-permission android:name="android.permission.HARDWARE_TEST" >
</uses-permission>

如果要想监听USB连接动作,在相应的activity加上如下

(qwm_usb_xml为要监听的设备信息,例如:<usb-device product-id="30507" vendor-id="2965" />):

<activityandroid:name=".MainActivity"android:label="@string/app_name" ><intent-filter><!-- usb设备的动作 --><action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter><!-- android设备的信息过滤 --><meta-dataandroid:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"android:resource="@xml/qwm_usb_xml" ></meta-data></activity>

2.必须USB设备先连接(此处为USB打印机),

usbManager.getDeviceList();

才能获得连接设备的信息。具体参数说明;

vendor-id  (VID):(此处为USB打印机)产商id
     product-id (PID):(此处为USB打印机)产品id

3.打印需要用的两个类,分别为:UsbDeviceConnection和UsbEndpoint;

贴上代码:

package com.tastykhana.usbprinter;import android.annotation.SuppressLint;import android.app.Activity;
import android.app.Notification.Action;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;import java.util.HashMap;
import java.util.Iterator;/*** @author qiwenming* @date 2016/2/25 0025 上午 10:37* @ClassName: UsbDemoActivity* @PackageName: com.qwm.qwmprinterdemo* @Description: usb练习*/
public class MainActivity extends Activity {private String TAG = MainActivity.class.getName();private UsbManager usbManager;private EditText usbDevicesTv;/*** 满足的设备*/private UsbDevice myUsbDevice;/*** usb接口*/private UsbInterface usbInterface;/*** 块输出端点*/private UsbEndpoint epBulkOut;private UsbEndpoint epBulkIn;/*** 控制端点*/private UsbEndpoint epControl;/*** 中断端点*/private UsbEndpoint epIntEndpointOut;private UsbEndpoint epIntEndpointIn;/*** 连接*/private UsbDeviceConnection myDeviceConnection;Button connect,send,print;private PendingIntent mPermissionIntent;//  private static final String ACTION_USB_PERMISSION =//            "com.Android.example.USB_PERMISSION";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);usbDevicesTv = (EditText) findViewById(R.id.usb_device_tv);send=(Button) findViewById(R.id.send);connect=(Button) findViewById(R.id.connect);print=(Button) findViewById(R.id.print);connect.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//连接usb//1)创建usbManagerusbManager = (UsbManager)getSystemService(Context.USB_SERVICE);//2)获取到所有设备 选择出满足的设备enumeraterDevices();//3)查找设备接口getDeviceInterface();//4)获取设备endpointassignEndpoint();//5)打开conn连接通道openDevice();}});send.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//6.发送数据 String xx = "0D";new Thread(new Runnable() {@Overridepublic void run() {try{String message="你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国你好中国"+"\n";String ms2="absfsngngndnndmhfmfmjfmjmfjj";sendMessageToPoint(message.getBytes("gbk"));}catch (Exception e){}}}).start();}});}/*** 枚举设备*/@SuppressLint("NewApi")public void enumeraterDevices(){HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();StringBuilder sb = new StringBuilder();while(deviceIterator.hasNext()){UsbDevice device = deviceIterator.next();sb.append(devicesString(device));
//                    sb.append(device.toString());
//                    sb.append("\n\n");if (device.getVendorId() !=3034&&device.getVendorId() !=2965&&device.getVendorId() !=26728&&device.getVendorId() !=33923 ) {myUsbDevice = device; // 获取USBDevice,此处为筛选去掉我当前设备已连接的USB设备,不通设备筛选的不同。}
//            if (device.getVendorId() == 1171 && device.getProductId() == 34656) {
//                myUsbDevice = device; // 获取USBDevice
//            }}usbDevicesTv.setText(sb.toString());}/*** usb设备的信息* @param device* @return*/@SuppressLint("NewApi")public String devicesString(UsbDevice device){StringBuilder builder = new StringBuilder("UsbDevice\nName=" + device.getDeviceName() +"\nVendorId=" + device.getVendorId() + "\nProductId=" + device.getProductId() +"\nmClass=" + device.getClass() + "\nmSubclass=" + device.getDeviceSubclass() +"\nmProtocol=" + device.getDeviceProtocol() + "\nmManufacturerName=" +"\nmSerialNumber=" +"\n\n");return builder.toString();}/*** 获取设备的接口*/@SuppressLint("NewApi")private void getDeviceInterface() {if(myUsbDevice!=null){Log.i(TAG,"interfaceCounts : "+myUsbDevice.getInterfaceCount());usbInterface = myUsbDevice.getInterface(0);System.out.println("成功获得设备接口:" + usbInterface.getId());Log.e("USB:", "成功获得设备接口:" + usbInterface.getId());}}/*** 分配端点,IN | OUT,即输入输出;可以通过判断*/@SuppressLint("NewApi")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;}}}}/*** 连接设备*/@SuppressLint("NewApi")public void openDevice() {if(usbInterface!=null){//接口是否为null// 在open前判断是否有连接权限;对于连接权限可以静态分配,也可以动态分配权限UsbDeviceConnection conn = null;if(usbManager.hasPermission(myUsbDevice)){//有权限,那么打开conn = usbManager.openDevice(myUsbDevice);}else {//没有权限,申请权限mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED), 0);usbManager.requestPermission(myUsbDevice, mPermissionIntent);if(usbManager.hasPermission(myUsbDevice)){//有权限,那么打开conn = usbManager.openDevice(myUsbDevice);}}if(null==conn){Toast.makeText(this,"不能连接到设备",Toast.LENGTH_SHORT).show();return;}//打开设备if(conn.claimInterface(usbInterface,true)){myDeviceConnection = conn;if (myDeviceConnection != null)// 到此你的android设备已经连上zigbee设备System.out.println("open设备成功!");final String mySerial = myDeviceConnection.getSerial();System.out.println("设备serial number:" + mySerial);} else {System.out.println("无法打开连接通道。");Toast.makeText(this,"无法打开连接通道。",Toast.LENGTH_SHORT).show();conn.close();}}}/*** 发送数据* @param buffer*/@SuppressLint("NewApi")public void sendMessageToPoint(byte[] buffer) {if(myDeviceConnection.bulkTransfer(epBulkOut,buffer,buffer.length,0) >= 0){//0 或者正数表示成功Toast.makeText(this,"发送成功",Toast.LENGTH_SHORT).show();}else{Toast.makeText(this,"发送失败的",Toast.LENGTH_SHORT).show();}}
}

Android USB打印机相关推荐

  1. android usb打印机a4,打印机随身带 全球最小A4打印机试用

    在单位或者办公室里,一般都会配备打印机等办公设备,来处理日常办公需要的资料,但是如果是出差或者是在特殊的环境中需要打印资料,但是周围又没有打印设备怎么办呢? 佳能在2008年4月份推出了新一代的便携式 ...

  2. android检测usb设备——usb打印机

    最近弄了一个安卓的项目,需要外接usb打印机,从网上找了一些方法,下面这个是测试了以后,没有问题的.主要是担心再次访问404,所以我做个备份,这里附一下原文链接. 在此之前,我先说几个我踩的坑. 这个 ...

  3. Android系统上部署usb打印机

    Android系统上部署usb打印机 一.综述 android系统现多用于手持设备,为手机等设备应用提供了很好的系统级支持.但对于PC机常用的打印功能,android到目前并不支持,也没有打印机厂家专 ...

  4. Android无法自动创建USB打印机节点/dev/usb/lp0【转】

    本文转载自:http://blog.csdn.net/u013686019/article/details/50165059 [html]  view plain  copy Android: 4.4 ...

  5. 基于AOA协议的android USB通信

    摘 要:AOA协议是Google公司推出的用于实现Android设备与外围设备之间USB通信的协议.该协议拓展了Android设备USB接口的功能,为基于Android系统的智能设备应用于数据采集和设 ...

  6. android usb弹窗权限r,Android USB权限对话框永远不会出现

    我写了一个简单的应用程序,通过USB将命令发送到连接到Android 4.0平板电脑的USB打印机.出于某种原因,我无法获得声明接口和打开连接的权限.这是相关的代码: public class Tes ...

  7. Android USB串口打印结账单小票

    最近在做打印小票的功能,需要通过USB串口连接打印机打印出订单的小票,自己也是在网上查了一些相关的资料,也踩了一些坑,最后把总结的代码分享出来,给有需要的朋友做个参考,废话不多说了,先看打印出来的效果 ...

  8. android usb联接网络打印机,打印到USB或预先选择的网络打印机从嵌入式android

    我的产品是使用嵌入式Android的工业测量仪器.仪器需要将结果打印到预先选定的网络打印机或USB打印机.仪器操作员不能担负标准的Android打印机界面,并且云打印不可接受.我认为这种情况在嵌入式A ...

  9. Android调用打印机

    打印机其实和Android没有什么大的关系,和linux内核关联才是比较强的. 最终的结果是要在Android实现驱动打印机,但是一般调试一个新的驱动的流程是这样的:1.先在linux PC上进行测试 ...

  10. Android USB Accessory方案研究

    申明:本文部分内容为网络相关资料整理,并结合本人实际工作总结而成.请引用或者转载注明出处,对于文章内容有疑问请留言. Android Open Accessory Protocol1.0 Androi ...

最新文章

  1. 公司GitHub被封号,只因员工在伊朗开电脑,官方:将撤销被美制裁国家限制
  2. mysql为什么没有nvarchar,关于mysql:为什么不将每个VARCHAR指定为VARCHAR(65535)?
  3. Spark _29_SparkStreaming初始
  4. 剑指offer——复习1:二叉树三种遍历方式的迭代与递归实现
  5. Nginx缓存配置以及nginx ngx_cache_purge模块的使用
  6. Extjs介绍及视频教程
  7. 手机上将png转pdf_如何在Windows 10上将Android智能手机用作网络摄像头
  8. 使用NVivo完善定性编码的艺术
  9. 毕业论文知网查重心得体会——吐血奉献
  10. 南阳oj 58 bfs入门
  11. no input file specified 三种解决方法
  12. 手写jQuery轮播图插件,即拿即用,更多接口,更少代码实现你想要的轮播图~~
  13. ArcGIS中实现空间内插
  14. 如何计算每月还多少房贷
  15. 最实用整理!大数据搜索引擎工具有哪些?
  16. 计算机网络 - 网络中的基本概念
  17. host ntrip 千寻rtk_「图文教程」千寻RTK连接千寻cors账号的操作步骤
  18. redis主从读写分离replication复制数据+sentienl哨兵集群主备切换
  19. 微信小程序—仿淘宝热搜词在搜索框中轮播功能
  20. 【第183期】网友简历分析:转行没有经验,如何过HR这关?

热门文章

  1. 【SVM分类】基于改进鲸鱼算法优化最小二乘支持向量机实现数据分类matlab代码
  2. matlab中定义分段函数,matlab中定义带符号的分段函数
  3. 双态IT时代,你需要什么样的IT咨询服务?
  4. IIS无法启动计算机上的服务W3SVC如何修复、万维网发布服务(w3svc)已停止解决办法
  5. 调用百度图像识别api处理网络图片(文字识别)
  6. 编译原理实验二【语法分析程序设计】
  7. 经典教材《晶体管电路设计》
  8. 弹性法计算方法的mck法_经济学原理中讲到的中点法计算需求弹性是怎么回事
  9. 国家精品课程推荐|中山大学-地理信息系统概论
  10. MATLAB 神经网络函数