开发者

Android Honeycomb 3.2 detect MTP connection via USB

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

ACT开发者_StackOverflow社区ION_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!


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜