0

I want to detect if a phone is plugged into a pc or will be unplugged...so in my manifest i have:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="de.name.usbtest.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
    </intent-filter>
    </activity>

    <service
        android:name=".MyService"
        >
    </service>
</application>

My Service Class:

@Override
public void onCreate() {
    USBBroadcast usbTrigger = null;
    // create new USBTrigger()() and register for ACTION_USB_DEVICE_ATTACHED broadcasts
    usbTrigger = new USBBroadcast();
    registerReceiver(usbTrigger, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
}

My Broadcastreceiver:

@Override
public void onReceive(Context ctx, Intent intent) {
    String action = intent.getAction();
    Toast.makeText(ctx, "Received", Toast.LENGTH_SHORT).show();
}

and my Main Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent serviceIntent = new Intent(this, MyService.class);

    startService(serviceIntent);

    setContentView(R.layout.activity_main);

}

But i never see the Toast, when i plug in my phone...Anyone knows why?!

davidOhara
  • 1,008
  • 5
  • 17
  • 39

2 Answers2

1

You forgot to show() the Toast

Toast.makeText(ctx, "Received", Toast.LENGTH_SHORT).show();
Ion Aalbers
  • 7,830
  • 3
  • 37
  • 50
0

try using this

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

as mentioned in this post.

Community
  • 1
  • 1