本文转载自:https://blog.csdn.net/phoebe_2012/article/details/47025309
用代码实现断开Android手机USB连接
用代码 实现了一个小功能:断开android手机USB连接。
- <span style="white-space:pre"> </span>// 尝试断开USB连接
- boolean disconnectUSB() {
- String state = "none";// 禁用所有usb
- //String state = "adb";// 仅使用adb
- //String state = "mtp,adb";// 使用mtp与adb
- SystemProperties.set("sys.usb.config", state);
- // wait for the transition to complete.
- // give up after 1 second.
- for (int i = 0; i < 20; i++) {
- // State transition is done when sys.usb.state is set to the new configuration
- if (state.equals(SystemProperties.get("sys.usb.state"))) return true;
- SystemClock.sleep(50);
- }
- return false;
- }
也可通过反射机制进行调用,但其实最终实际执行的还是上面的代码。
- try {
- final int MSG_SET_CURRENT_FUNCTIONS = 2;
- IBinder usb_service = ServiceManager.getService(Context.USB_SERVICE);
- Class<?> c_UsbService = Helpers.findClass("com.android.server.usb.UsbService");
- Field f_mDeviceManager = Helpers.findField(c_UsbService, "mDeviceManager");
- Object o_mDeviceManager = f_mDeviceManager.get(usb_service);
- Class<?> c_UsbDeviceManager = Helpers.findClass("com.android.server.usb.UsbDeviceManager");
- Field f_mHandler = Helpers.findField(c_UsbDeviceManager, "mHandler");
- Object o_mHandler = f_mHandler.get(o_mDeviceManager);
- Handler h_mHandler = (Handler) o_mHandler;
- // 禁用adb
- Field f_mAdbEnabled = Helpers.findField(c_UsbDeviceManager, "mAdbEnabled");
- f_mAdbEnabled.setBoolean(o_mDeviceManager, false);
- // 不提供USB服务
- Message msg = Message.obtain(h_mHandler, MSG_SET_CURRENT_FUNCTIONS);
- msg.obj = new String("none");
- msg.arg1 = 0;
- h_mHandler.removeMessages(MSG_SET_CURRENT_FUNCTIONS);
- h_mHandler.sendMessage(msg);
- Log.d("test", "[End]try disconnect USB");
- return true;
- } catch (Throwable e) {
- e.printStackTrace();
- Log.e("test", "[disconnectUSB][Throwable]" + e.getMessage());
- }
- return false;