├── .gitignore
├── .idea
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── cn
│ │ └── xiaolongonly
│ │ └── usbhelper
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── cn
│ │ │ └── xiaolongonly
│ │ │ └── usbhelper
│ │ │ ├── MainActivity.java
│ │ │ └── usbmodule
│ │ │ ├── USBFinder.java
│ │ │ ├── USBMonitor.java
│ │ │ ├── USBPermissionUtil.java
│ │ │ ├── UsbOTGService.java
│ │ │ └── UsbPermissionReceiverListener.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── cn
│ └── xiaolongonly
│ └── usbhelper
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 |
45 | # Keystore files
46 | # Uncomment the following line if you do not want to check your keystore files in.
47 | #*.jks
48 |
49 | # External native build folder generated in Android Studio 2.2 and later
50 | .externalNativeBuild
51 |
52 | # Google Services (e.g. APIs or Firebase)
53 | google-services.json
54 |
55 | # Freeline
56 | freeline.py
57 | freeline/
58 | freeline_project_description.json
59 |
60 | # fastlane
61 | fastlane/report.xml
62 | fastlane/Preview.html
63 | fastlane/screenshots
64 | fastlane/test_output
65 | fastlane/readme.md
66 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 背景知识
2 | USB是一种数据通信方式,也是一种数据总线,而且是最复杂的总线之一。
3 | 硬件上,它是用插头连接。一边是公头(plug),一边是母头(receptacle)。例如,PC上的插座就是母头,USB设备使用公头与PC连接。
4 | 目前USB硬件接口分三种,普通PC上使用的叫Type;原来诺基亚功能机时代的接口为Mini USB;目前Android手机使用的Micro USB/TYPE-C。
5 |
6 | #### Host
7 | USB是由Host端控制整个总线的数据传输的。单个USB总线上,只能有一个Host。
8 | #### OTG
9 | On The Go,这是在USB2.0引入的一种mode,提出了一个新的概念叫主机协商协议(Host Negotiation Protocol),允许两个设备间商量谁去当Host。
10 |
11 | 想了解更多USB知识,请参考USB官网以及下面这篇文章:
12 | http://www.crifan.com/files/doc/docbook/usb_basic/release/html/usb_basic.html
13 |
14 | #### USB HOST/DEVICE/OTG概念:
15 |
16 | 1.USB 设备分为 HOST (主设备)和SLAVE (从设备),只有当一台 HOST 与一台 SLAVE 连接时才能实现数据的传输。
17 | (1) USBHOST 是指主机。
18 | (2) USBOTG 设备既能做主机,又能做设备。 OTG 技术就是实现在没有 Host 的情况下,实现从设备间的数据传送。
19 | 当 OTG 插到电脑上时. OTG 的角色就是连接电脑的 device (读卡器),也就是 SLAVE (从设备);当USB/SD device插到 OTG 上, OTG 的角色就是 HOST 主机。(有些手机也经常用到 OTG的功能)
20 |
21 | ### Android使用(Host连接)
22 | 首先应该介绍,USBManager这个类,这个类用于访问USB状态并与USB设备通信。目前只开放HOST模式。
23 | 初始化USBManager mUsbManager = ((UsbManager) context.getSystemService(USB_SERVICE));
24 | 里面有几个重要的方法:
25 |
26 | 1.getDeviceList()——获取当前USB连接从设备的列表,返回一个存储UsbDevice的HashMap
27 | 2.getAccessoryList()——这个就是获取Host的列表(用不到)
28 | 3.openDevice(UsbDevice)—— 这个方法是USB连接方法,连接成功后会返回一个UsbDeviceConnection对象。
29 | 4.requestPermission(UsbDevice,PendingIntent)——这个方法用于请求USB权限。
30 |
31 | #### 监听USB插入/拔出
32 | 通过广播意图android.hardware.usb.action.USB_STATE,实现插入拔出监听
33 | ```java
34 | class USBStateReceive extends BroadcastReceiver {
35 | public static final String ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE";
36 | public static final String USB_CONNECTED = "connected";
37 | private IUsbStateChangeListener mUsbStateChangeListener;
38 |
39 |
40 | public void onReceive(Context paramContext, Intent intent) {
41 | String action = intent.getAction();
42 | Log.d(TAG, "usb action + " + action);
43 | switch (action) {
44 | case UsbManager.ACTION_USB_DEVICE_ATTACHED:
45 | UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
46 | Log.d(TAG, "device_attached," + device.toString());
47 | if (mUsbStateChangeListener != null) {
48 | mUsbStateChangeListener.onAttach(device);
49 | }
50 | break;
51 | case UsbManager.ACTION_USB_DEVICE_DETACHED:
52 | device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
53 | Log.d(TAG, "device_detached," + device.toString());
54 | if (mUsbStateChangeListener != null) {
55 | mUsbStateChangeListener.onDetach(device);
56 | }
57 | break;
58 | case ACTION_USB_STATE:
59 | boolean connected = intent.getBooleanExtra(USB_CONNECTED, false);
60 | break;
61 | }
62 |
63 | }
64 |
65 | public void setUsbStateChangeListener(IUsbStateChangeListener usbStateChangeListener) {
66 | this.mUsbStateChangeListener = usbStateChangeListener;
67 | }
68 | }
69 |
70 | ```
71 | 这个广播也可以获取到当前插入/拔出的设备信息。可以通过这个广播来监听新插入/拔出的USB设备。
72 |
73 |
74 | #### 当前连接的USB设备
75 | 可以通过getDeviceList获取当前连接的USB设备
76 | 为此我们编写一个USBFinder 用来查找USB设备。
77 | ```java
78 |
79 | package cn.xiaolongonly.usbhelper.usbmodule;
80 |
81 | import android.hardware.usb.UsbDevice;
82 | import android.hardware.usb.UsbManager;
83 |
84 | import java.util.HashMap;
85 | import java.util.Iterator;
86 |
87 | /**
88 | *
89 | *
90 | * @author xiaolong 719243738@qq.com
91 | * @version v1.0
92 | * @since 2019/4/10 15:36
93 | */
94 | public class USBFinder {
95 | private UsbManager mUsbManager;
96 | private static USBFinder usbFinder;
97 |
98 | private USBFinder(UsbManager usbManager) {
99 | this.mUsbManager = usbManager;
100 | }
101 |
102 | /**
103 | * Application Context;
104 | *
105 | */
106 | public static void init(UsbManager usbManager) {
107 | usbFinder = new USBFinder(usbManager);
108 | }
109 |
110 | public static USBFinder getInstance() {
111 | if (usbFinder == null) {
112 | throw new RuntimeException("需要在Application中執行USBFinder.init()");
113 | }
114 | return usbFinder;
115 | }
116 |
117 | public HashMap findUsbMap() {
118 | HashMap deviceMap = mUsbManager.getDeviceList();
119 | return deviceMap;
120 | }
121 |
122 |
123 | public UsbDevice findUsbDevice(int vendorId, int productId) {
124 | HashMap deviceMap = mUsbManager.getDeviceList();
125 | Iterator iterator = deviceMap.values().iterator();
126 | UsbDevice localUsbDevice;
127 | while (iterator.hasNext()) {
128 | localUsbDevice = (UsbDevice) iterator.next();
129 | if (localUsbDevice.getVendorId() == vendorId || localUsbDevice.getProductId() == productId) {
130 | return localUsbDevice;
131 | }
132 | }
133 | return null;
134 | }
135 | }
136 |
137 | ```
138 | 1. findUsbMap 用于找到当前已连接的USB设备列表,这个用户选择连接非常有用,比如有多个USB设备,选择一个连接。(跟上一个通过广播监听的区别是,有时候一些USB设备默认是插着的,通过上面的广播并不能知道)
139 | 2. findUsbDevice 遍历设备列表,通过vendorId和productId找到合适的USB设备,通过这个可以省掉让用户选择的过程,如果连接的设备只有一个的话可以直接用这个。
140 |
141 |
142 | #### USB连接,如何确认USB连接及USB授权?
143 | Android 在USBManager 提供了一个 requestPermission(UsbDevice device, PendingIntent pi),这个模式是手机作为HOST对设备做授权。
144 |
145 | ```java
146 | public void getPermission(Context context, UsbManager usbManager, UsbDevice usbDevice, final UsbPermissionReceiverListener callBack) {
147 | if (usbManager.hasPermission(usbDevice)) {
148 | callBack.onSuccessful();
149 | return;
150 | }
151 | mContext = context;
152 | IntentFilter intentFilter = new IntentFilter();
153 | intentFilter.addAction("com.android.example.USB_PERMISSION");
154 | mContext.registerReceiver(mUsbReceiver, intentFilter);//注册广播接收者
155 | mUsbReceiver.setUsbPermissionReceiverListener(new UsbPermissionReceiverListener() {
156 | @Override
157 | public void onSuccessful() {
158 | mContext.unregisterReceiver(mUsbReceiver);
159 | callBack.onSuccessful();
160 | }
161 |
162 | @Override
163 | public void onFail(String msg) {
164 | mContext.unregisterReceiver(mUsbReceiver);
165 | callBack.onFail(msg);
166 | }
167 |
168 | });
169 | mUsbReceiver.setUsbDeviceName(usbDevice.getDeviceName());//为广播接受者设置DeviceName名称用于与接收的名称进行对比
170 | PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
171 | usbManager.requestPermission(usbDevice, mPermissionIntent);
172 | }
173 | ```
174 | 授权广播
175 | ```java
176 | class PermissionReceiver extends BroadcastReceiver {
177 |
178 | protected UsbPermissionReceiverListener mUsbPeramissionRecevierListener = null;
179 | protected String mUsbDeviceName = "";
180 |
181 | public void onReceive(Context paramContext, Intent intent) {
182 | String action = intent.getAction();
183 | Log.d(TAG, "usb action + " + action);
184 |
185 | if (intent == null) {
186 | mUsbPeramissionRecevierListener.onFail("授权失败:未知授权申请!");
187 | } else {
188 | if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
189 | UsbDevice localUsbDevice = intent.getParcelableExtra("device");
190 | if (localUsbDevice != null) {
191 | if (!(intent.getBooleanExtra("permission", false))) {//用户取消授权
192 | if (this.mUsbPeramissionRecevierListener != null) {
193 | mUsbPeramissionRecevierListener.onFail("用户取消授权,授权失败!");
194 | }
195 | } else {
196 | String deviceName = localUsbDevice.getDeviceName();
197 | if (deviceName.equals(this.mUsbDeviceName)) {//若获得的deviceName与_usbDeviceName一致
198 | if (this.mUsbPeramissionRecevierListener != null) {
199 | mUsbPeramissionRecevierListener.onSuccessful();
200 | }
201 | } else {
202 | if (this.mUsbPeramissionRecevierListener != null) {
203 | mUsbPeramissionRecevierListener.onFail("授權失敗:設備名稱不一致!");
204 | }
205 | }
206 | }
207 | } else {
208 | return;
209 | }
210 | } else {
211 | mUsbPeramissionRecevierListener.onFail("授權失敗:未知授权申请!");
212 | return;
213 | }
214 | }
215 | }
216 |
217 |
218 | public void setUsbPermissionReceiverListener(UsbPermissionReceiverListener paramAsyncTaskListener) {
219 | this.mUsbPeramissionRecevierListener = paramAsyncTaskListener;
220 | }
221 |
222 | public void setUsbDeviceName(String usbDeviceName) {
223 | this.mUsbDeviceName = usbDeviceName;
224 | }
225 | }
226 | ```
227 | 授权广播类,监听的是com.android.example.USB_PERMISSION
228 |
229 | 通过以上几个方法我们可以获取到当前连接的USB设备了,接下来就是建立传输通道
230 |
231 | #### 数据传输
232 |
233 | 这边先要获取一个UsbDeviceConnection 对象, 也就是通过USBManager.openDevice(UsbDevice)获取连接的对象。
234 |
235 | ```java
236 | /**
237 | * 选择USB设备和interface,打开。
238 | *
239 | * @return
240 | */
241 | public int open(UsbDevice usbDevice, int interfaceIndex) {
242 | mDevice = usbDevice;
243 | if (!setInterface(this.mDevice, interfaceIndex)) {
244 | Log.d(TAG, "interfaceIndex OutOfBound!");
245 | return -1;
246 | }
247 | this.mInterface = mDevice.getInterface(interfaceIndex);
248 | if (!(setEndpoint(this.mInterface))) {
249 | return -1;
250 | }
251 | this.mDeviceConnection = this.mManager.openDevice(usbDevice);
252 | if (this.mDeviceConnection == null) {
253 | return -1;
254 | }
255 | return 0;
256 | }
257 | ```
258 |
259 | 讲一下为什么这个类需要传interfaceIndex,一般来讲一个UsbDevice 会有多个UsbInterface, 不同的interface是分开的,有不同的功能。每个UsbInterface又会有多个UsbEndpoint,用于处理输入和输出,也就是数据传输。
260 |
261 | 检验interface和endpoint 是否符合
262 | ```java
263 | protected boolean setInterface(UsbDevice mDevice, int interfaceIndex) {
264 | if (mDevice != null && mDevice.getInterfaceCount() > interfaceIndex) {
265 | return true;
266 | } else {
267 | return false;
268 | }
269 | }
270 |
271 |
272 | /**
273 | * 设置Endpoint,根据Device的Interface
274 | *
275 | * @param paramUsbInterface
276 | * @return
277 | */
278 | protected boolean setEndpoint(UsbInterface paramUsbInterface) {
279 | if (paramUsbInterface.getEndpointCount() != 2) {
280 | Log.d(TAG, "Endpoint count less than 2..");
281 | return false;
282 | }
283 | for (int m = 0; m < paramUsbInterface.getEndpointCount(); m++) {
284 | UsbEndpoint ep = paramUsbInterface.getEndpoint(m);
285 | if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
286 | if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
287 | this.mEndpointOut = ep;
288 | } else {
289 | this.mEndpointIn = ep;
290 | }
291 | } else {
292 | return false;
293 | }
294 | }
295 | return true;
296 | }
297 | ```
298 |
299 | 这两个方法就是用来看是不是能找到对应的UsbInterface和UsbEndpoint,因为我们的需求是要这个既有输入又有输出的UsbInterface。所以做了相应的校验。
300 |
301 | 接下来是数据传输
302 | ```java
303 | public void sendData(byte[] data, IDataSendCallBack iDataSendCallBack, int timeOut) {
304 | if (this.mDeviceConnection == null) {
305 | if (iDataSendCallBack != null) {
306 | iDataSendCallBack.onSendResult(CODE_DEVICE_NO_OPEN, null, "未开启设备,请先执行open()!");
307 | }
308 |
309 | }
310 | this.mDeviceConnection.claimInterface(this.mInterface, true);//调用了本地
311 | bulkTransfer(this.mDeviceConnection, this.mEndpointOut, this.mEndpointIn, data, data.length, timeOut, iDataSendCallBack);
312 | this.mDeviceConnection.releaseInterface(this.mInterface);//释放接口
313 |
314 | }
315 |
316 | protected void bulkTransfer(final UsbDeviceConnection usbDeviceConnection, UsbEndpoint outPoint, final UsbEndpoint inPoint, byte[] datas, int dataLength, final int timeLimit, final IDataSendCallBack iDataSendCallBack) {
317 | int bulkTransferLength = usbDeviceConnection.bulkTransfer(outPoint,
318 | datas, dataLength, timeLimit);
319 | if (bulkTransferLength < 0) {
320 | if (iDataSendCallBack != null) {
321 | iDataSendCallBack.onSendResult(CODE_SEND_FAIL, datas, "发送失败!");
322 | }
323 | }
324 | if (iDataSendCallBack != null) {
325 | iDataSendCallBack.onSendResult(CODE_SEND_SUCCESS, datas, "發送成功!");
326 |
327 | }
328 | if (mEndpointIn == null) {
329 | if (iDataSendCallBack != null) {
330 | iDataSendCallBack.onSendResult(CODE_NO_INPOINT, null,
331 | "該interface底下沒有接口端口,无法接收数据!");
332 | }
333 | }
334 | new Thread(new Runnable() {
335 |
336 | @Override
337 | public void run() {
338 | while (true) {
339 | byte[] inByte = new byte[1024];
340 | int inLength = usbDeviceConnection.bulkTransfer(inPoint,
341 | inByte, inByte.length, timeLimit);
342 | if (inLength > 0) {
343 | inByte = Arrays.copyOf(inByte, inLength);
344 | if (iDataSendCallBack != null) {
345 | iDataSendCallBack.onSendResult(CODE_DATA_RECEIVE,
346 | inByte, "收到数据!");
347 | }
348 | } else {
349 | break;
350 | }
351 | }
352 | }
353 | }).start();
354 | }
355 | ```
356 | DeviceConnection.claimInterface()占用了这个interface,在发送结束后releaseInterface 相当于释放interface.
357 | 项目要求是一次输入,一次输出。所以每次都会开开合合,如果不是这种需求的话应该可以长期开着等全部结束后关闭,类似于Socket。
358 |
359 | Talk is cheap, here the code.
360 |
361 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 | defaultConfig {
6 | applicationId "cn.xiaolongonly.usbhelper"
7 | minSdkVersion 16
8 | targetSdkVersion 28
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(dir: 'libs', include: ['*.jar'])
23 | implementation 'com.android.support:appcompat-v7:28.0.0'
24 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
25 | testImplementation 'junit:junit:4.12'
26 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
27 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
28 | }
29 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/cn/xiaolongonly/usbhelper/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("cn.xiaolongonly.usbhelper", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/xiaolongonly/usbhelper/MainActivity.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 |
6 | import cn.xiaolongonly.usbhelper.usbmodule.USBMonitor;
7 |
8 | public class MainActivity extends AppCompatActivity {
9 |
10 | @Override
11 | protected void onCreate(Bundle savedInstanceState) {
12 | super.onCreate(savedInstanceState);
13 | setContentView(R.layout.activity_main);
14 | USBMonitor.init(getApplicationContext());
15 | //写一个USBMonitor把之前的功能聚合,然后可以在做一些扩展。
16 | USBMonitor usbMonitor=USBMonitor.getInstance();
17 | usbMonitor.findDeviceList(); //——获取列表
18 | usbMonitor.connectState();//当前连接状态
19 | // usbMonitor.findDevice(); //获取指定设备
20 | // usbMonitor.permissionConnect(); //连接指定设备
21 |
22 | // usbMonitor.sendData();//发送数据
23 |
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/xiaolongonly/usbhelper/usbmodule/USBFinder.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper.usbmodule;
2 |
3 | import android.hardware.usb.UsbDevice;
4 | import android.hardware.usb.UsbManager;
5 |
6 | import java.util.HashMap;
7 | import java.util.Iterator;
8 |
9 | /**
10 | *
11 | *
12 | * @author xiaolong 719243738@qq.com
13 | * @version v1.0
14 | * @since 2019/4/10 15:36
15 | */
16 | public class USBFinder {
17 | private UsbManager mUsbManager;
18 | private static USBFinder usbFinder;
19 |
20 | private USBFinder(UsbManager usbManager) {
21 | this.mUsbManager = usbManager;
22 | }
23 |
24 | /**
25 | * Application Context;
26 | *
27 | */
28 | public static void init(UsbManager usbManager) {
29 | usbFinder = new USBFinder(usbManager);
30 | }
31 |
32 | public static USBFinder getInstance() {
33 | if (usbFinder == null) {
34 | throw new RuntimeException("需要在Application中執行USBFinder.init()");
35 | }
36 | return usbFinder;
37 | }
38 |
39 | public HashMap findUsbMap() {
40 | HashMap deviceMap = mUsbManager.getDeviceList();
41 | return deviceMap;
42 | }
43 |
44 |
45 | public UsbDevice findUsbDevice(int vendorId, int productId) {
46 | HashMap deviceMap = mUsbManager.getDeviceList();
47 | Iterator iterator = deviceMap.values().iterator();
48 | UsbDevice localUsbDevice;
49 | while (iterator.hasNext()) {
50 | localUsbDevice = (UsbDevice) iterator.next();
51 | if (localUsbDevice.getVendorId() == vendorId || localUsbDevice.getProductId() == productId) {
52 | return localUsbDevice;
53 | }
54 | }
55 | return null;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/xiaolongonly/usbhelper/usbmodule/USBMonitor.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper.usbmodule;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.content.IntentFilter;
7 | import android.hardware.usb.UsbDevice;
8 | import android.hardware.usb.UsbManager;
9 | import android.util.Log;
10 |
11 | import java.util.HashMap;
12 |
13 | import static android.content.Context.USB_SERVICE;
14 | import static cn.xiaolongonly.usbhelper.usbmodule.USBMonitor.USBStateReceive.ACTION_USB_STATE;
15 |
16 | /**
17 | * <描述功能>
18 | *
19 | * @author xiaolong 719243738@qq.com
20 | * @version v1.0
21 | * @since 2019/4/15 9:24
22 | */
23 | public class USBMonitor {
24 | private static final String TAG = USBMonitor.class.getSimpleName();
25 | public static final int DEAULT_WAIT_TIME = 10;
26 | public static final int DEFAULT_MAX_SEND_TIMES = 2;
27 | private Context mContext;
28 | private static USBMonitor instance = null;
29 | private UsbManager mUsbManager;
30 | private boolean mOpenState = false;
31 | private UsbOTGService mService;
32 | private USBFinder mUsbFinder;
33 |
34 | private USBStateReceive usbStateReceive;
35 |
36 | public static USBMonitor getInstance() {
37 | return instance;
38 | }
39 |
40 | public static void init(Context context) {
41 | instance = new USBMonitor(context);
42 | }
43 |
44 |
45 | /**
46 | * 初始化,判断蓝牙状态
47 | *
48 | * @param context
49 | */
50 | private USBMonitor(Context context) {
51 | this.mContext = context;
52 | mUsbManager = ((UsbManager) context.getSystemService(USB_SERVICE));
53 | UsbOTGService.init(mUsbManager);
54 | mService = UsbOTGService.getInstance();
55 | USBFinder.init(mUsbManager);
56 | mUsbFinder = USBFinder.getInstance();
57 | registerReceiver(mContext);
58 | }
59 |
60 |
61 | /**
62 | * 注册蓝牙扫描广播接收器
63 | */
64 | private void registerReceiver(Context context) {
65 | IntentFilter intentFilter = new IntentFilter();
66 | intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
67 | intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
68 | intentFilter.addAction(ACTION_USB_STATE);
69 | context.registerReceiver(usbStateReceive = new USBStateReceive(), intentFilter);
70 | }
71 |
72 | public void setUsbStateChangeListener(IUsbStateChangeListener usbStateListener) {
73 | if (usbStateReceive != null) {
74 | usbStateReceive.setUsbStateChangeListener(usbStateListener);
75 | }
76 | }
77 |
78 |
79 | /**
80 | * 通过权限开启
81 | *
82 | * @param usbDevice
83 | * @param interfaceIndex
84 | */
85 | public void permissionConnect(final UsbDevice usbDevice, final int interfaceIndex, final UsbPermissionReceiverListener usbPermissionReceiverListener) {
86 | if (usbDevice == null) {
87 | usbPermissionReceiverListener.onFail("未找到USB设备,启动失败");
88 | return;
89 | }
90 | if (!mUsbManager.hasPermission(usbDevice)) {
91 | USBPermissionUtil.getInstance().getPermission(mContext, mUsbManager, usbDevice, new UsbPermissionReceiverListener() {
92 | @Override
93 | public void onSuccessful() {
94 | openUsbDevice(usbDevice, interfaceIndex, usbPermissionReceiverListener);
95 | }
96 |
97 | @Override
98 | public void onFail(String msg) {
99 | usbPermissionReceiverListener.onFail(msg);
100 | mOpenState = false;
101 | }
102 | });
103 | } else {
104 | openUsbDevice(usbDevice, interfaceIndex, usbPermissionReceiverListener);
105 | }
106 |
107 | }
108 |
109 | /**
110 | * 开启打开USB
111 | *
112 | * @param usbDevice
113 | * @param interfaceIndex
114 | * @param usbPermissionReceiverListener
115 | */
116 | private void openUsbDevice(UsbDevice usbDevice, int interfaceIndex, UsbPermissionReceiverListener usbPermissionReceiverListener) {
117 | int openCode = mService.open(usbDevice, interfaceIndex);
118 | if (openCode != 0) {
119 | // Toast.makeText(mContext, "打开失败," + openCode, Toast.LENGTH_SHORT).show();
120 | usbPermissionReceiverListener.onFail("打开失败," + openCode);
121 | mOpenState = false;
122 | } else {
123 | mOpenState = true;
124 | usbPermissionReceiverListener.onSuccessful();
125 | }
126 | }
127 |
128 |
129 | public void sendData(byte[] data, UsbOTGService.IDataSendCallBack iDataSendCallBack, int timeOut) {
130 | if (mService == null) {
131 | return;
132 | }
133 | mService.sendData(data, iDataSendCallBack, timeOut);
134 | }
135 |
136 | public void disconnected() {
137 | if (mService != null) {
138 | mService.close();
139 | }
140 | instance = null;
141 | destroyReceiver();
142 | }
143 |
144 |
145 | /**
146 | * 獲取全部鏈接USB設備
147 | *
148 | * @return
149 | */
150 | public HashMap findDeviceList() {
151 | return mUsbFinder.findUsbMap();
152 | }
153 |
154 |
155 | /**
156 | * 獲取單個USB設備
157 | *
158 | * @return
159 | */
160 | public UsbDevice findDevice(int vendorId, int productId) {
161 | return mUsbFinder.findUsbDevice(vendorId, productId);
162 | }
163 |
164 |
165 | /**
166 | * 解除广播接收器
167 | */
168 | private void destroyReceiver() {
169 | if (usbStateReceive != null) {
170 | mContext.unregisterReceiver(usbStateReceive);
171 | }
172 |
173 | }
174 |
175 | /**
176 | * USB接入的兩種狀態 但是接入設備不一定是指定設備。
177 | * attach 接入
178 | * detach 移除
179 | */
180 | public interface IUsbStateChangeListener {
181 | void onAttach(UsbDevice device);
182 |
183 | void onDetach(UsbDevice device);
184 | }
185 |
186 | public boolean connectState() {
187 | return mOpenState;
188 | }
189 |
190 | class USBStateReceive extends BroadcastReceiver {
191 | public static final String ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE";
192 | public static final String USB_CONNECTED = "connected";
193 | private IUsbStateChangeListener mUsbStateChangeListener;
194 |
195 |
196 | public void onReceive(Context paramContext, Intent intent) {
197 | String action = intent.getAction();
198 | Log.d(TAG, "usb action + " + action);
199 | switch (action) {
200 | case UsbManager.ACTION_USB_DEVICE_ATTACHED:
201 | UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
202 | Log.d(TAG, "device_attached," + device.toString());
203 | if (mUsbStateChangeListener != null) {
204 | mUsbStateChangeListener.onAttach(device);
205 | }
206 | break;
207 | case UsbManager.ACTION_USB_DEVICE_DETACHED:
208 | device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
209 | Log.d(TAG, "device_detached," + device.toString());
210 | if (mUsbStateChangeListener != null) {
211 | mUsbStateChangeListener.onDetach(device);
212 | }
213 | break;
214 | case ACTION_USB_STATE:
215 | boolean connected = intent.getBooleanExtra(USB_CONNECTED, false);
216 | break;
217 | }
218 |
219 | }
220 |
221 | public void setUsbStateChangeListener(IUsbStateChangeListener usbStateChangeListener) {
222 | this.mUsbStateChangeListener = usbStateChangeListener;
223 | }
224 | }
225 |
226 | }
227 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/xiaolongonly/usbhelper/usbmodule/USBPermissionUtil.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper.usbmodule;
2 |
3 | import android.app.PendingIntent;
4 | import android.content.BroadcastReceiver;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.content.IntentFilter;
8 | import android.hardware.usb.UsbDevice;
9 | import android.hardware.usb.UsbManager;
10 | import android.util.Log;
11 |
12 | /**
13 | * <权限工具>
14 | *
15 | * @author xiaolong 719243738@qq.com
16 | * @version v1.0
17 | * @since 2019/4/11 16:41
18 | */
19 | public class USBPermissionUtil {
20 | private static final String TAG = USBPermissionUtil.class.getSimpleName();
21 | public static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
22 |
23 | private PermissionReceiver mUsbReceiver = new PermissionReceiver();
24 | private Context mContext;
25 | private final static USBPermissionUtil M_USB_PERMISSION_UTIL = new USBPermissionUtil();
26 |
27 | public static USBPermissionUtil getInstance() {
28 | return M_USB_PERMISSION_UTIL;
29 | }
30 |
31 | public void getPermission(Context context, UsbManager usbManager, UsbDevice usbDevice, final UsbPermissionReceiverListener callBack) {
32 | if (usbManager.hasPermission(usbDevice)) {
33 | callBack.onSuccessful();
34 | return;
35 | }
36 | mContext = context;
37 | IntentFilter intentFilter = new IntentFilter();
38 | intentFilter.addAction("com.android.example.USB_PERMISSION");
39 | mContext.registerReceiver(mUsbReceiver, intentFilter);//注册广播接收者
40 | mUsbReceiver.setUsbPermissionReceiverListener(new UsbPermissionReceiverListener() {
41 | @Override
42 | public void onSuccessful() {
43 | mContext.unregisterReceiver(mUsbReceiver);
44 | callBack.onSuccessful();
45 | }
46 |
47 | @Override
48 | public void onFail(String msg) {
49 | mContext.unregisterReceiver(mUsbReceiver);
50 | callBack.onFail(msg);
51 | }
52 |
53 | });
54 | mUsbReceiver.setUsbDeviceName(usbDevice.getDeviceName());//为广播接受者设置DeviceName名称用于与接收的名称进行对比
55 | PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
56 | usbManager.requestPermission(usbDevice, mPermissionIntent);
57 | }
58 |
59 |
60 | class PermissionReceiver extends BroadcastReceiver {
61 |
62 | protected UsbPermissionReceiverListener mUsbPeramissionRecevierListener = null;
63 | protected String mUsbDeviceName = "";
64 |
65 | public void onReceive(Context paramContext, Intent intent) {
66 | String action = intent.getAction();
67 | Log.d(TAG, "usb action + " + action);
68 |
69 | if (intent == null) {
70 | mUsbPeramissionRecevierListener.onFail("授权失败:未知授权申请!");
71 | } else {
72 | if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
73 | UsbDevice localUsbDevice = intent.getParcelableExtra("device");
74 | if (localUsbDevice != null) {
75 | if (!(intent.getBooleanExtra("permission", false))) {//用户取消授权
76 | if (this.mUsbPeramissionRecevierListener != null) {
77 | mUsbPeramissionRecevierListener.onFail("用户取消授权,授权失败!");
78 | }
79 | } else {
80 | String deviceName = localUsbDevice.getDeviceName();
81 | if (deviceName.equals(this.mUsbDeviceName)) {//若获得的deviceName与_usbDeviceName一致
82 | if (this.mUsbPeramissionRecevierListener != null) {
83 | mUsbPeramissionRecevierListener.onSuccessful();
84 | }
85 | } else {
86 | if (this.mUsbPeramissionRecevierListener != null) {
87 | mUsbPeramissionRecevierListener.onFail("授權失敗:設備名稱不一致!");
88 | }
89 | }
90 | }
91 | } else {
92 | return;
93 | }
94 | } else {
95 | mUsbPeramissionRecevierListener.onFail("授權失敗:未知授权申请!");
96 | return;
97 | }
98 | }
99 | }
100 |
101 |
102 | public void setUsbPermissionReceiverListener(UsbPermissionReceiverListener paramAsyncTaskListener) {
103 | this.mUsbPeramissionRecevierListener = paramAsyncTaskListener;
104 | }
105 |
106 | public void setUsbDeviceName(String usbDeviceName) {
107 | this.mUsbDeviceName = usbDeviceName;
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/xiaolongonly/usbhelper/usbmodule/UsbOTGService.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper.usbmodule;
2 |
3 | import android.hardware.usb.UsbConstants;
4 | import android.hardware.usb.UsbDevice;
5 | import android.hardware.usb.UsbDeviceConnection;
6 | import android.hardware.usb.UsbEndpoint;
7 | import android.hardware.usb.UsbInterface;
8 | import android.hardware.usb.UsbManager;
9 | import android.util.Log;
10 |
11 | import java.util.Arrays;
12 |
13 | /**
14 | * <底层控制工具>
15 | *
16 | * @author xiaolong 719243738@qq.com
17 | * @version v1.0
18 | * @since 2019/4/11 9:45
19 | */
20 | public class UsbOTGService {
21 | private static final String TAG = UsbOTGService.class.getSimpleName();
22 |
23 | public final static int CODE_DATA_RECEIVE = 0x61;
24 | public final static int CODE_DEVICE_NO_OPEN = 0x65;
25 | public final static int CODE_SEND_SUCCESS = 0X66;
26 | public final static int CODE_NO_INPOINT = 0X67;
27 | public final static int CODE_SEND_FAIL = 0X68;
28 | public final static int CODE_OUT_OF_TIME = 0X69;
29 | private UsbManager mManager;
30 | private UsbDevice mDevice;
31 | private UsbDeviceConnection mDeviceConnection;
32 | private UsbEndpoint mEndpointIn;
33 | private UsbEndpoint mEndpointOut;
34 | private UsbInterface mInterface;
35 |
36 | private static UsbOTGService usbOTGService;
37 |
38 |
39 |
40 | private UsbOTGService(UsbManager usbManager) {
41 | this.mManager = usbManager;
42 | }
43 |
44 | public static void init(UsbManager usbManager) {
45 | usbOTGService = new UsbOTGService(usbManager);
46 | }
47 |
48 | public static UsbOTGService getInstance() {
49 | if (usbOTGService == null) {
50 | throw new RuntimeException("需要在Application中執行UsbOTGService.init()");
51 | }
52 | return usbOTGService;
53 | }
54 |
55 | public void sendData(byte[] data, IDataSendCallBack iDataSendCallBack, int timeOut) {
56 | if (this.mDeviceConnection == null) {
57 | if (iDataSendCallBack != null) {
58 | iDataSendCallBack.onSendResult(CODE_DEVICE_NO_OPEN, null, "未开启设备,请先执行open()!");
59 | }
60 |
61 | }
62 | this.mDeviceConnection.claimInterface(this.mInterface, true);//调用了本地
63 | bulkTransfer(this.mDeviceConnection, this.mEndpointOut, this.mEndpointIn, data, data.length, timeOut, iDataSendCallBack);
64 | this.mDeviceConnection.releaseInterface(this.mInterface);//释放接口
65 |
66 | }
67 |
68 | protected void bulkTransfer(final UsbDeviceConnection usbDeviceConnection, UsbEndpoint outPoint, final UsbEndpoint inPoint, byte[] datas, int dataLength, final int timeLimit, final IDataSendCallBack iDataSendCallBack) {
69 | int bulkTransferLength = usbDeviceConnection.bulkTransfer(outPoint,
70 | datas, dataLength, timeLimit);
71 | if (bulkTransferLength < 0) {
72 | if (iDataSendCallBack != null) {
73 | iDataSendCallBack.onSendResult(CODE_SEND_FAIL, datas, "发送失败!");
74 | }
75 | }
76 | if (iDataSendCallBack != null) {
77 | iDataSendCallBack.onSendResult(CODE_SEND_SUCCESS, datas, "發送成功!");
78 |
79 | }
80 | if (mEndpointIn == null) {
81 | if (iDataSendCallBack != null) {
82 | iDataSendCallBack.onSendResult(CODE_NO_INPOINT, null,
83 | "該interface底下沒有接口端口,无法接收数据!");
84 | }
85 | }
86 | new Thread(new Runnable() {
87 |
88 | @Override
89 | public void run() {
90 | while (true) {
91 | byte[] inByte = new byte[1024];
92 | int inLength = usbDeviceConnection.bulkTransfer(inPoint,
93 | inByte, inByte.length, timeLimit);
94 | if (inLength > 0) {
95 | inByte = Arrays.copyOf(inByte, inLength);
96 | if (iDataSendCallBack != null) {
97 | iDataSendCallBack.onSendResult(CODE_DATA_RECEIVE,
98 | inByte, "收到数据!");
99 | }
100 | } else {
101 | break;
102 | }
103 | }
104 | }
105 | }).start();
106 | }
107 |
108 | /**
109 | * 关闭mDeviceConnection
110 | */
111 | public void close() {
112 | this.mDeviceConnection.close();
113 | }
114 |
115 |
116 | /**
117 | * 选择USB设备和interface,打开。
118 | *
119 | * @return
120 | */
121 | public int open(UsbDevice usbDevice, int interfaceIndex) {
122 | mDevice = usbDevice;
123 | if (!setInterface(this.mDevice, interfaceIndex)) {
124 | Log.d(TAG, "interfaceIndex OutOfBound!");
125 | return -1;
126 | }
127 | this.mInterface = mDevice.getInterface(interfaceIndex);
128 | if (!(setEndpoint(this.mInterface))) {
129 | return -1;
130 | }
131 | this.mDeviceConnection = this.mManager.openDevice(usbDevice);
132 | if (this.mDeviceConnection == null) {
133 | return -1;
134 | }
135 | return 0;
136 | }
137 |
138 |
139 | protected boolean setInterface(UsbDevice mDevice, int interfaceIndex) {
140 | if (mDevice != null && mDevice.getInterfaceCount() > interfaceIndex) {
141 | return true;
142 | } else {
143 | return false;
144 | }
145 | }
146 |
147 |
148 | /**
149 | * 设置Endpoint,根据Device的Interface
150 | *
151 | * @param paramUsbInterface
152 | * @return
153 | */
154 | protected boolean setEndpoint(UsbInterface paramUsbInterface) {
155 | if (paramUsbInterface.getEndpointCount() != 2) {
156 | Log.d(TAG, "Endpoint count less than 2..");
157 | return false;
158 | }
159 | for (int m = 0; m < paramUsbInterface.getEndpointCount(); m++) {
160 | UsbEndpoint ep = paramUsbInterface.getEndpoint(m);
161 | if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
162 | if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
163 | this.mEndpointOut = ep;
164 | } else {
165 | this.mEndpointIn = ep;
166 | }
167 | } else {
168 | return false;
169 | }
170 | }
171 | return true;
172 | }
173 |
174 | public interface IDataSendCallBack {
175 | void onSendResult(int code, byte[] data, String msg);
176 | }
177 | }
178 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/xiaolongonly/usbhelper/usbmodule/UsbPermissionReceiverListener.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper.usbmodule;
2 |
3 | /**
4 | * <描述功能>
5 | *
6 | * @author xiaolong 719243738@qq.com
7 | * @version v1.0
8 | * @since 2019/4/11 16:41
9 | */
10 | public interface UsbPermissionReceiverListener {
11 | void onSuccessful();
12 |
13 | void onFail(String msg);
14 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | UsbHelper
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/cn/xiaolongonly/usbhelper/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package cn.xiaolongonly.usbhelper;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | google()
6 | jcenter()
7 |
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.4.1'
11 |
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | jcenter()
21 |
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
15 |
16 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guoxiaolongonly/USBHelper/825a63cc550eeccf1074cb5b822b7f9bf1b4c580/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Jun 21 16:52:23 CST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------