本文介绍了Android串口通信封装之OkUSB的示例代码,分享给大家。具体如下:
Github传送门:OkUSB
OkUSB
一个简洁的Android串口通信框架。
功能简介
用法简介
Gradle
allprojects { repositories { ... maven { url 'https://jitpack.io' } } } dependencies { compile 'com.github.zhouzhuo810:OkUSB:1.0.0' }
具体用法
1.在AndroidManifest.xml中添加如下特性:
在需要连接串口的Activity中添加:
2.在res文件夹创建xml文件夹,新建device_filter.xml
3.前面都是准备工作,这里才真正使用。
//初始化 usb = new USB.USBBuilder(this) .setBaudRate(115200) //波特率 .setDataBits(8) //数据位 .setStopBits(UsbSerialPort.STOPBITS_1) //停止位 .setParity(UsbSerialPort.PARITY_NONE) //校验位 .setMaxReadBytes(20) //接受数据最大长度 .setReadDuration(500) //读数据间隔时间 .setDTR(false) //DTR enable .setRTS(false) //RTS enable .build(); //实现监听连接状态和数据收发。 usb.setOnUsbChangeListener(new USB.OnUsbChangeListener() { @Override public void onUsbConnect() { Toast.makeText(MainActivity.this, "conencted", Toast.LENGTH_SHORT).show(); } @Override public void onUsbDisconnect() { Toast.makeText(MainActivity.this, "disconencted", Toast.LENGTH_SHORT).show(); } @Override public void onDataReceive(byte[] data) { tvResult.setText(new String(data, Charset.forName("GB2312"))); } @Override public void onUsbConnectFailed() { Toast.makeText(MainActivity.this, "connect fail", Toast.LENGTH_SHORT).show(); } @Override public void onPermissionGranted() { Toast.makeText(MainActivity.this, "permission ok", Toast.LENGTH_SHORT).show(); } @Override public void onPermissionRefused() { Toast.makeText(MainActivity.this, "permission fail", Toast.LENGTH_SHORT).show(); } @Override public void onDriverNotSupport() { Toast.makeText(MainActivity.this, "no driver", Toast.LENGTH_SHORT).show(); } @Override public void onWriteDataFailed(String error) { Toast.makeText(MainActivity.this, "write fail" + error, Toast.LENGTH_SHORT).show(); } @Override public void onWriteSuccess(int num) { Toast.makeText(MainActivity.this, "write ok " + num, Toast.LENGTH_SHORT).show(); } });
4.如果是Activity,可以在onDestroy中调用如下代码关闭串口。
if (usb != null) { usb.destroy(); }
License
Copyright 2017 zhouzhuo810 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔