allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
引用 implementation'com.github.mik3y:usb-serial-for-android:3.3.0' 库文件
权限
代码:
/**
* create nano on 2020/12/19 23:10
*/
public class UsbActivity extends BaseActivity {
/**
* 初始化根布局
*
* @return 布局layout的id
*/
@Override
public int initContentView() {
return R.layout.activity_usb;
}
@Override
public void initView() {
super.initView();
register();
search();
}
@Override
public void initClick() {
super.initClick();
binding.usbBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(usbDevicesList!=null && usbDevicesList.size()>0){
mUsbSerialPort = usbDevicesList.get(0);
RequestNormalPermission(usbManager, mUsbSerialPort.getDriver().getDevice());
}else{
ToastUtils.showToast("未找到usb设备");
}
}
});
binding.usbClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// byte[] bys = {(byte) 0xA0, 0x01, 0x00, (byte) 0xA1};
byte[] bys = {(byte) 0xA0, 0x01, 0x01, (byte) 0xA2};
sendData(bys);
}
});
binding.usbOpen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
byte[] bys = {(byte) 0xA0, 0x01, 0x00, (byte) 0xA1};
sendData(bys);
}
});
}
private String USB_PERMISSION = "com.android.usb.USB_PERMISSION";
private PendingIntent mPrtPermissionIntent; //获取外设权限的意图
/**
* 动态注册usb广播,拔插动作,注册动作
*/
private void register() {
//注册在此service下的receiver的监听的action
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
intentFilter.addAction(USB_PERMISSION);
registerReceiver(usbReceiver, intentFilter);//注册receiver
//通知监听外设权限注册状态
//PendingIntent:连接外设的intent
//ask permission
mPrtPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(USB_PERMISSION), 0);
}
private BroadcastReceiver usbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) {
return;
}
String action = intent.getAction();
// USB注册动作
if (USB_PERMISSION.equals(action)) {
synchronized (this) {
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if ((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) != null) {
// usbDev = (UsbDevice)
// intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
// after request dev permission and granted
// pemission , connect printer by usb
LogUtil.i("after request dev permission and granted pemission , connect printer by usb.");
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
List drivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
UsbDevice device = drivers.get(0).getDevice();
UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
mUsbSerialPort = driver.getPorts().get(0);
getUsbInfo(mUsbSerialPort.getDriver().getDevice());
} else {
LogUtil.e("usb device suddenly disappera.");
ToastUtils.showToast("USB外设意外消失。");
}
} else {
LogUtil.e("usb permission granted fail.");
ToastUtils.showToast("USB权限注册失败。");
}
}
}
// USB拔插动作
else if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)
|| UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
LogUtil.i("USB 插入...");
search();
}
}
};
UsbManager usbManager;
List usbDevicesList = new ArrayList<>();
//查询设备
private void search() {
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
List drivers =
UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
//try get enable printer dev
if (drivers.size() > 0) {
usbDevicesList.clear();
for (UsbSerialDriver driver : drivers) {
usbDevicesList.addAll(driver.getPorts());
}
// adapter.notifyDataSetChanged();
} else {
LogUtil.e("not find device.");
return;
}
}
UsbSerialPort mUsbSerialPort;
UsbDeviceConnection usbDeviceConnection;
/**
* 请求权限:一般来说有弹框
*/
public void RequestNormalPermission(UsbManager usbManager, UsbDevice device) {
if (!usbManager.hasPermission(device)) {
// ask has dev permission,pop dialog
LogUtil.d("printer dev has no permission,try request it.");
ToastUtils.showToast("printer dev has no permission,try request it.");
usbManager.requestPermission(device, mPrtPermissionIntent);// will recall mReceiver
} else {
// when dev has granted permission , connect printer by usb
LogUtil.d("printer dev has granted permission,connect usb.");
ToastUtils.showToast("USB权限注册成功。");
UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
mUsbSerialPort = driver.getPorts().get(0);
getUsbInfo(mUsbSerialPort.getDriver().getDevice());
}
}
/**
* 获得授权USB的基本信息
* 1、USB接口,一般是第一个
* 2、USB设备的输入输出端
*/
private void getUsbInfo(UsbDevice usbDevice) {
StringBuilder sb = new StringBuilder();
if (Build.VERSION.SDK_INT >= 23) {
sb.append(String.format("VID:%04X PID:%04X ManuFN:%s PN:%s V:%s",
usbDevice.getVendorId(),
usbDevice.getProductId(),
usbDevice.getManufacturerName(),
usbDevice.getProductName(),
usbDevice.getVersion()
));
} else if (Build.VERSION.SDK_INT >= 21) {
sb.append(String.format("VID:%04X PID:%04X ManuFN:%s PN:%s",
usbDevice.getVendorId(),
usbDevice.getProductId(),
usbDevice.getManufacturerName(),
usbDevice.getProductName()
));
} else {
sb.append(String.format("VID:%04X PID:%04X",
usbDevice.getVendorId(),
usbDevice.getProductId()
));
}
LogUtil.d("获得授权USB的基本信息: " + sb.toString());
connect();//连接
}
/**
* usb设备的连接
*/
private void connect() {
LogUtil.i("usb connect...");
usbDeviceConnection = null;
usbDeviceConnection = usbManager.openDevice(mUsbSerialPort.getDriver().getDevice());
if (usbDeviceConnection == null) {
// ll_usb_connect.setVisibility(View.GONE);
// tv_usb.setText(tv_usb.getText().toString() + " 连接失败!!!");
ToastUtils.showToast("连接失败");
} else {
// tv_usb.setText(tv_usb.getText().toString() + " 连接成功。");
// ll_usb_connect.setVisibility(View.VISIBLE);
// tv_connect_state.setText("USB通信");
// tv_receive.setText("");
// et_send.setText("01 03 00 01 00 01 D5 CA");
ToastUtils.showToast("连接成功");
setConnectionParam();
onDeviceStateChange();
}
}
/**
* 设置通讯参数
*/
private void setConnectionParam() {
try {
if (mUsbSerialPort.getDriver().getDevice().getInterfaceCount() > 0) {
mUsbSerialPort.open(usbDeviceConnection);
//9600 就是波特率
mUsbSerialPort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
StringBuilder sb = new StringBuilder();
sb.append("\n CD - Carrier Detect = " + mUsbSerialPort.getCD());
sb.append("\n CTS - Clear To Send = " + mUsbSerialPort.getCTS());
sb.append("\n DSR - Data Set Ready = " + mUsbSerialPort.getDSR());
sb.append("\n DTR - Data Terminal Ready = " + mUsbSerialPort.getDTR());
sb.append("\n DSR - Data Set Ready = " + mUsbSerialPort.getDSR());
sb.append("\n RI - Ring Indicator = " + mUsbSerialPort.getRI());
sb.append("\n RTS - Request To Send = " + mUsbSerialPort.getRTS());
// tv_connect_state.setText(sb.toString());
LogUtil.d(sb.toString());
try {
mUsbSerialPort.setDTR(true);
} catch (IOException x) {
LogUtil.e("IOException DTR: " + x.getMessage());
}
try {
mUsbSerialPort.setRTS(true);
} catch (IOException x) {
LogUtil.e("IOException RTS: " + x.getMessage());
}
}
//无通讯接口
else {
// tv_connect_state.setText("该USB无通讯接口");
ToastUtils.showToast("该USB无通讯接口");
}
} catch (IOException e) {
LogUtil.e("Error setting up device: " + e.getMessage());
// tv_connect_state.setText("Error opening device: " + e.getMessage());
ToastUtils.showToast("Error opening device: " + e.getMessage());
try {
mUsbSerialPort.close();
} catch (IOException e2) {
// Ignore.
}
mUsbSerialPort = null;
return;
}
}
public boolean sendData(byte[] data) {
LogUtil.i("sendData:" + Arrays.toString(data));
if (mSerialIoManager != null) {
// mSerialIoManager.writeAsync(data);
try {
mUsbSerialPort.write(data, 2000);
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
private final SerialInputOutputManager.Listener mListener =
new SerialInputOutputManager.Listener() {
@Override
public void onRunError(Exception e) {
LogUtil.d("Runner stopped.");
}
@Override
public void onNewData(final byte[] data) {
LogUtil.i("onReceiver data=" + Arrays.toString(data));
// instance.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// tv_receive.setText(HexUtil.bytesToHexString(data));
// }
// });
}
};
/**
* usb设备断开连接
*/
private void disconnect() {
LogUtil.e("usb disconnect...");
stopIoManager();
if (mUsbSerialPort != null) {
try {
mUsbSerialPort.close();
} catch (IOException e) {
// Ignore.
}
mUsbSerialPort = null;
}
//usbdevice usbmanager
}
private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
private SerialInputOutputManager mSerialIoManager;
private void stopIoManager() {
if (mSerialIoManager != null) {
LogUtil.i("Stopping io manager ..");
mSerialIoManager.stop();
mSerialIoManager = null;
}
}
private void startIoManager() {
if (mSerialIoManager == null) {
LogUtil.i("Starting io manager ..");
mSerialIoManager = new SerialInputOutputManager(mUsbSerialPort, mListener);
mExecutor.submit(mSerialIoManager);
}
}
private void onDeviceStateChange() {
stopIoManager();
startIoManager();
}
@Override
public void onDestroy() {
unregisterReceiver(usbReceiver);
usbReceiver = null;
disconnect();
super.onDestroy();
}
}
public class LogUtil {
public static void i(String ss){
Log.d("liu",ss);
}
public static void e(String ss){
i(ss);
}
public static void d(String ss){
i(ss);
}
}
布局文件 activity_usb.xml