Android: Detecting USB

前端 未结 6 1858
一生所求
一生所求 2020-11-27 06:13

Is there any way to know(programmatically) in your Activity/Application that the user has connected your phone to PC through USB?

6条回答
  •  悲&欢浪女
    2020-11-27 06:48

    The main problem while checking android.intent.action.ums_connected is that devices using the MTP protocol (such as the Samsung Nexus Galaxy) don't receive this broadcast.

    This is why I'm using another way to detect when the Smartphone is plugged or unplugged:

    I check the batery state. There is an intent called ACTION_BATTERY_CHANGED called when an event happens on the battery. In this intent there are some extra fields containing some informations. One of them is EXTRA_PLUGGED:

    Indicating whether the device is plugged in to a power source; 0 means it is on battery, other constants are different types of power sources.
    

    The other constants are BATTERY_PLUGGED_AC and BATTERY_PLUGGED_USB

    So with this broadcast you can know if the Smartphone has been plugged in USB even if it uses the MTP protocol.

    To know if the Smartphone is unplugged you juste have to check when the EXTRA_PLUGGED value changes from BATTERY_PLUGGED_USB to 0

提交回复
热议问题