Detect USB connection

.

This is a sample program to show the broadcast notification that USB connected and disconnected. Last topic published in this forum is Location Manager

Underlying Algorithm:

Basic description of algorithm in step by step form:
1.) Create a Project DetactUSB.
2.) Create a class DetactUSB.java, which will extends BroadcastReceiver.
3.) Put the following code in DetactUSB.java:

package com.app.DetactUSB;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;

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();
	}
    } 
}

4.) Add receiver in AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.app.DetactUSB"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.INTERNET">
    </uses-permission>
    <uses-permission android:name="android.permission.RECORD_AUDIO">
    </uses-permission>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
       <activity android:name=".MyActivity" android:label="@string/app_name">
		<intent-filter>
		     <action android:name="android.intent.action.MAIN" />
		     <category android:name="android.intent.category.LAUNCHER" />
		</intent-filter>
	</activity>
    <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>
    </application>
</manifest>

5.) To detect USB :

android.intent.action.UMS_CONNECTED
android.intent.action.UMS_DISCONNECTED

6.) Run the application.

Steps to Create:

1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. DetactUSB. Enter following information:
Project name: DetactUSB
Build Target: Android 2.1
Application name: DetactUSB
Package name: com.app.DetactUSB
Create Activity: MyActivity

On Clicking Finish DetactUSB code structure is generated with the necessary Android Packages being imported along with MyActivity.java. MyActivity class will look like following:

package com.app.DetactUSB;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity 
{
	/** Called when the activity is first created. */
	@Override
        public void onCreate(Bundle savedInstanceState) 
	{
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
	}
}

Output : The final output will look like following :

About the Author

Leave a Reply 20 comments

Kasi - July 9, 2011 Reply

i am fully confused with this code… How the activity changes from MyActivity.java to DetactUSB.java…. and also we need to add MyActivity.java to android manifest file…. i have done all these… but it is still showing an error “the application has stopped unexpectdely” plz help on this topic….

    Sushant - July 9, 2011 Reply

    When you set a receiver in your activity (DetactUSB for above example) and define filters in it as we did

    <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>
    

    on launching your app your main activity (MyActivity in this case) will call that receiver internally on receiving defined intents or actions. This is how and why activity changes from MyActivity.java to DetactUSB.java.

    There is no need to add manually MyActivity.java into your manifest as it gets added automatically when you create project.

     <activity android:name=".MyActivity" android:label="@string/app_name">
                    <intent-filter>
                         <action android:name="android.intent.action.MAIN" />
                         <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
     </activity>    
     

    If you still getting some force close check you manifest permissions and send me the “logcat” results.

    Thanks.

rain - November 11, 2011 Reply

Thank you for this nice post. It helped me alot.

Ramkumar - November 23, 2011 Reply

Is it possible to deactivate USB connection when service of my apps running..

Mike Trethowan - November 25, 2011 Reply

Hi. I have created a project using your example. I am debugging on a BeagleBoard xM running Rowboat which has 4USB Host ports and one USB Device port which is used for ADB connections. I can compile and run the program from Eclipse, but I get no indication that the app is detecting USB activity. I have tried two separate devices, one is a FTDI R232 interface cable, the other a thumb drive with an activity LED. When plugging in the thumb drive it’s activity light flashes indicating communication is taking place. In Debug and DDMS I can see the app running, but I see no activity when I insert or remove a device. Any thoughts? Thank You.

p.s. Once I get this figured out, I plan to extend this out to a Microchip DM240415 Demo Board for Android.

Mike Trethowan - November 25, 2011 Reply

Hi. I have created a project using your example. I am debugging on a BeagleBoard xM running Rowboat which has 4USB Host ports and one USB Device port which is used for ADB connections. I can compile and run the program from Eclipse, but I get no indication that the app is detecting USB activity. I have tried two separate devices, one is a FTDI R232 interface cable, the other a thumb drive with an activity LED. When plugging in the thumb drive it’s activity light flashes indicating communication is taking place. In Debug and DDMS I can see the app running, but I see no activity when I insert or remove a device. Any thoughts? Thank You.

p.s. Once I get this figured out, I plan to extend this out to a Microchip DM240415 Demo Board for Android.

Mike Trethowan - November 25, 2011 Reply

Sorry, I didn’t double post. The first post gave me an error that I entered the wrong security code. When I reentered, the screen refreshed and the double post appeared. Thanks

what is android - January 29, 2012 Reply

Hello there, You’ve performed a fantastic job. I will certainly digg it and in my opinion recommend to my friends. I’m sure they will be benefited from this site.

игры для android - February 5, 2012 Reply

Very great post. I just stumbled upon your weblog and wanted to say that I’ve really enjoyed surfing around your blog posts. After all I will be subscribing on your rss feed and I’m hoping you write again very soon!

Обзор китайских товаров - February 12, 2012 Reply

Thanks , I’ve just been searching for information about this subject for a long time and yours is the best I have discovered so far. But, what concerning the bottom line? Are you positive about the supply?|What i do not realize is in reality how you are now not actually a lot more neatly-appreciated than you might be now. You are very intelligent.

Mike Trethowan - February 20, 2012 Reply

I guess this topic is obsolete

bhavik - April 4, 2012 Reply

can u send me the code for this example.

Tuyen - April 27, 2012 Reply

please help to me, I copy the same code, but not run, i don’t know why, my android 3.2

ips - June 22, 2012 Reply

its a not working

AJ - June 25, 2012 Reply

hi i can’t start the program. i’m using android 2.1 but a notice keep popping out after i start the program stating that an error has occurred. please help.

Hannes - August 13, 2012 Reply

Seems UMS_CONNECTED is deprecated. I tried MEDIA_MOUNTED but cant seem to get it to work. Any suggestions. Thanks

mudit srivastava - October 22, 2012 Reply

this code is not working in 2.3.3 as the “usb connected” is not displaying on the screen. please help me to solve the error.

LauraBacu - December 3, 2012 Reply

hello, i’m quite new in android programming, i’m trying to learn how to configure the usb access and permissions to let my app comunicate with a serial port ftdi by usb. i’ve copy your code but i have another main class and i dont know how to call the class DetactUSB.java to make it works. thanks!!

LauraBacu - December 3, 2012 Reply

now i’ve understood the change of class that you explain in answer 2. but when i connect the usb doesnt appear any toast or any text. can you help me? thanks!

KrihsnaKanth - February 15, 2013 Reply

It is working for me!!!!!! But if i uninstall app and run again it is not working. :( I don’t know why. But i do suggest that the 2 permissions “android.permission.INTERNET” and “android:name=”android.permission.RECORD_AUDIO” are not required ….. :).

Leave a Reply: