【问题标题】:Why won't my Broadcast Receiver detect a USB Connection?为什么我的广播接收器无法检测到 USB 连接?
【发布时间】:2020-05-15 06:02:44
【问题描述】:

我有一个广播接收器,它正在我的应用程序中侦听 USB 连接事件。代码如下:

BroadcastReceiver mUsbReceiver; //Initialized elsewhere
void registerMyReceiver() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    this.registerReceiver(this.mUsbReceiver, filter);
}

此代码在一些 设备上运行良好,但在其他设备上运行良好。平板电脑等较大的设备似乎比手机更成功。

为什么此接收器会在某些设备上检测到 USB 连接,而在其他设备上检测不到?

【问题讨论】:

    标签: android broadcastreceiver android-usb


    【解决方案1】:

    虽然像 this 这样的答案提供了所需的电缆和所需的引脚连接的见解,而 this 提供了有关驱动程序和不良电缆的先决条件的信息,但都没有回答我上面提出的核心问题。

    Android Docs 提供了有关如何在检测到设备后访问设备的信息,但对于我实际连接设备的问题没有任何帮助。

    答案来自this article,其中指出:

    We have identified 3 requirements for an Android device to support USB Host Mode and be able to communicate 
    with [The USB Device]:
    
    [1] The Android device must be running version 4.1 (Jelly Bean) of the OS, or higher.
    [2] The output power on the Android device's USB port should be 5V.
    [3] The configuration file android.hardware.usb.host.xml must exist on the Android device in the folder
     /system/etc/permissions. The presence of this configuration file is what enables USB 
    Host Mode on your Android device.
    

    第三点是我想提请注意的,因为有问题的xml文件是这个:

    <?xml version="1.0" encoding="utf-8"?>
    <!-- Copyright (C) 2011 The Android Open Source Project
    
         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.
    -->
    
    <!-- This is the standard feature indicating that the device can communicate
        with USB devices as the USB host. -->
    <permissions>
        <feature name="android.hardware.usb.host" />
    </permissions>
    

    如您所见,这是一个简单的 XML 文件。但正如this answer 所述,它需要在根级别完成才能访问它。

    这里的结果是操作系统需要在内核级别将此文件设置到正确的目录中,或者需要在事后植根并放入设备。

    这两种解决方案之一将解决此问题。

    【讨论】:

      【解决方案2】:

      对于像 Samsung S3 Neo 这样的一些设备,我使用这种外部供电的 USB OTG 集线器解决了 USB 端口缺少 5V 的问题 [2]:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多