Search code examples
androidusbsd-card

How to check if USB connected mode is enabled on android?


I have an app on the android market and users often connect their devices to their computers to add music into the apps folder.

I have specifically stated in the instructions that android apps cannot communicate with the SD card while USB connected mode is enabled. Apparently this is not stupid proof enough.

Is there a way to detect in java if the USB is connected? I have seen it done with broadcast receivers, but this is such a stupid way to do it. This won't work if the user starts the app after connecting to USB. There has got to be a better way.


Solution

  • This is similar to this: Check USB Connection Status on Android

    Although they do make use of Broadcast Receivers. You say this is a stupid way of doing things, but can you be more specific about that?

    It is not the case that you can't detect it after the app has started. What you would need to do would be to put

    <intent-filter>
    <action android:name="android.intent.action.ACTION_UMS_CONNECTED"/>
    <action android:name="android.intent.action.ACTION_UMS_DISCONNECTED"/>
    

    in your AndroidManifest.xml underneath the <Receiver> entry for the following class:

    public class IntentReceiver extends BroadcastReceiver {
    
            @Override
    
            public void onReceive(Context context, Intent intent) {
    
                    // TODO Auto-generated method stub
    
                    if(intent.getAction().equals(Intent.ACTION_UMS_CONNECTED)){
    
                            Toast.makeText(context, "mounted", Toast.LENGTH_LONG).show();
    
                            Intent myStarterIntent = new Intent(context, tst.class);
    
                             myStarterIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
                            context.startActivity(myStarterIntent);
    
                    }
    
            }
    
    }
    

    `

    Sources Cited: http://www.anddev.org/start_activity_on_usb_connect-t8814.html