Android Honeycomb 3.2 detect MTP connection via USB

陌路散爱 提交于 2019-12-14 03:53:16

问题


I saw other posts about detecting a USB connection, but they didn't talk about MPT specifically and just a more general detection so I figured I'd ask specifically about MTP.

I'm connecting my Xoom to the computer via USB and I want my app to write a file out when the MTP connection is established. When the USB is disconnected and the MTP server has stopped I want to write out another file.

So I want to detect both the connected and not connected cases. I can't seem to find any kinds of intents that are sent when this happens.

I saw some intests listed on android.developer such as:

ACTION_MEDIA_SHARED

ACTION_UMS_CONNECTED

ACTION_UMS_DISCONNECTED

but these are used for USB mass storage and the Xoom does MTP and not USB mass storage.

This should be possible when you see logcat output as USB connection is logged along with the MTP server starting and stopping.

D/Vold ( 85): USB disconnected

D/Tethering( 155): InitialState.processMessage what=4

D/Tethering( 155): sendTetherStateChangedBroadcast 0, 0, 0

D/MtpService( 2674): stopping MTP server

D/Tethering( 155): sendTetherStateChangedBroadcast 1, 0, 0

D/Tethering( 155): interfaceAdded :usb0

D/MtpService( 2674): addStorageLocked 65537 /mnt/sdcard

D/MtpService( 2674): starting MTP server

D/MtpService( 2674): addStorageLocked 65537 /mnt/sdcard

D/Vold ( 85): USB connected

Does anybody know how I can accomplish my goal? Even the ability to detect USB Connected/Disconnected would probably work for me though as I saw in some other posts this doesn't seem possible.

Thanks!


回答1:


I was wondering the same thing and I came up with an alternative:

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




回答2:


Listen to this broadcast android.hardware.usb.action.USB_STATE I have tested it and it works with PTP or MTP enabled device. there is a boolean extra "connected" that will tell you if USB cable is connected or not.



来源:https://stackoverflow.com/questions/7182986/android-honeycomb-3-2-detect-mtp-connection-via-usb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!