Android:如何以编程方式连接/断开OTG [英] Android : How to programmatically connect/disconnect OTG

查看:214
本文介绍了Android:如何以编程方式连接/断开OTG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连接&在我的android设备中以编程方式断开USB OTG(笔驱动器,硬盘驱动器等)

I want to connect & disconnect USB OTG (pen drive, hard drive etc) programmatically in my android device

对于USB,当我连接到PC时,我使用以下路径来绑定/取消绑定USB

For USB, I'm using the following path to bind/unbind USB when connected to PC

/sys/bus/usb/drivers/usb/bind or unbind

我想为OTG做同样的事情.

In the same way I want to do it for OTG.

推荐答案

如果您在设备上具有root用户访问权限,则可以使用我发现的几种方法.在应用程序中,您需要调用以下内容:

If you have root access on the device you can use a few methods I have found. In the app you would need to call something like:

String[] commandConfigValue0 = { "su", "-c", "echo 0 > /sys/bus/usb/drivers/usb/usb1/bConfigurationValue", };
String[] commandConfigValue0 = { "su", "-c", "echo 0 > /sys/bus/usb/drivers/usb/usb1/bConfigurationValue", };   
String[] commandConfigValue1 = { "su", "-c", "echo 1 > /sys/bus/usb/drivers/usb/usb1/bConfigurationValue", };
String[] commandAuthorized0 = { "su", "-c", "echo 0 > /sys/bus/usb/drivers/usb/usb1/authorized", };
String[] commandAuthorized1 = { "su", "-c", "echo 1 > /sys/bus/usb/drivers/usb/usb1/authorized", };
Process p;
    try {
        p = Runtime.getRuntime().exec(commandAuthorized0);
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        Log.d("MainActivity", "From unbind: " + in.toString());

        // I don't think "rebinding" works here but if you listen for the usb disconnect you can then call this second runtime command to bind the internal usbhub
        Thread.sleep(3000);

        p = Runtime.getRuntime().exec(commandAuthorized1);
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        Log.d("MainActivity", "From bind: " + in.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我查看了一些我自己的没有根目录的较新设备,它们也具有/sys/bus/usb/drivers/usb/usb2,并且可能存在具有/sys/bus/usb/drivers/usb/usb3的设备.因此,根据要运行应用程序的设备,您可能必须执行几次呼叫.

I have looked at some newer devices that I own that are not rooted that also have /sys/bus/usb/drivers/usb/usb2 and there may be devices with /sys/bus/usb/drivers/usb/usb3. So you may have to run through several calls depending on the devices you are wanting your app to run on.

如果您希望在没有root访问权限的情况下执行此操作.我还在努力寻找解决方案!

If you are looking to do it without root access. I am still trying to find that solution as well!

祝你好运!

这篇关于Android:如何以编程方式连接/断开OTG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆