java – How to detect USB connection via application?


Is it possible for me to detect a USB connection in my Android application and how do I do it?

I have a sync menu that is done via USB and FTP, however I want to make the USB option accessible only when the device is connected to the PC via USB.

I saw something about USBManager, but I couldn't find anything that could help me.


In the Activity that has this menu, do the following:

Declare a class derived from BroadcastReceiver

public class UsbDeviceDetect extends BroadcastReceiver { 

    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equalsIgnoreCase( "android.intent.action.UMS_CONNECTED")) {

                //Aqui torne enable o seu item de menu
        if (intent.getAction().equalsIgnoreCase( "android.intent.action.UMS_DISCONNECTED")) {

                //Aqui torne disable o seu item menu

Declare two attributes, one for BroadcastReceiver and one for IntentFilter

private UsbDeviceDetect usbDeviceDetect;
private IntentFilter filter;

In the onCreate method create an instance of BroadcastReceiver and its IntentFilter

protected void onCreate(Bundle savedInstanceState) {

    UsbDeviceDetect usbDeviceDetect = new UsbDeviceDetect();
    filter = new IntentFilter();


In the method onResume register the BroadcastReceiver

protected void onResume(){

    registerReceiver(usbDeviceDetect, filter));

In the onPause method unregister the BroadcastReceiver

protected void onPause() {


Scroll to Top