0

I am working on a Android project. I need a small help in that. Can some one guide me how do i check if the USB port is enabled or not in the Android device.

Thanks in Advance

user1814512
  • 67
  • 2
  • 7

1 Answers1

1

You need to use BroadCastReceiver with following actions,

<receiver android:name=".DetactUSB">
   <intent-filter>
        <action android:name="android.intent.action.UMS_CONNECTED" />
        <action android:name="android.intent.action.UMS_DISCONNECTED" />
   </intent-filter>
</receiver>

In the BroadcastReceiver you can code like below to check,

public class DetactUSB extends BroadcastReceiver
{ 
    private static final String TAG = "DetactUSB";
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        // TODO Auto-generated method stub
        if (intent.getAction().equalsIgnoreCase( "android.intent.action.UMS_CONNECTED"))
        {
                TextView textView = new TextView(context);
                textView.setBackgroundColor(Color.MAGENTA);
                textView.setTextColor(Color.BLUE);
                textView.setPadding(10,10,10,10);
                textView.setText("USB connected……….");
                Toast toastView = new Toast(context);
                toastView.setDuration(Toast.LENGTH_LONG);
                toastView.setGravity(Gravity.CENTER, 0,0);
                toastView.setView(textView);
                toastView.show();
                Log.i(TAG,"USB connected..");
        }
        if (intent.getAction().equalsIgnoreCase( "android.intent.action.UMS_DISCONNECTED"))
        {
                TextView textView = new TextView(context);
                textView.setBackgroundColor(Color.MAGENTA);
                textView.setTextColor(Color.BLUE);
                textView.setPadding(10,10,10,10);
                textView.setText("USB Disconnected……….");
                Toast toastView = new Toast(context);
                toastView.setDuration(Toast.LENGTH_LONG);
                toastView.setGravity(Gravity.CENTER, 0,0);
                toastView.setView(textView);
                toastView.show();
        }
    } 
}
Lucifer
  • 29,392
  • 25
  • 90
  • 143