Auto start android java application when USB is connected to mobile?

61 views Asked by At

I'm trying to start an android application whenever any hardware is connected to mobile's USB port.

What I'm doing is creating a BroadcastReceiver and and registering it in the AndroidManifest.xml

<receiver android:name=".MyBroadcastReceiver"
    android:exported="true">
    <intent-filter>
          <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
    </intent-filter>
    <meta-data
          android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
          android:resource="@xml/device-filter" />
</receiver>

and inside onReceive() method of BroadcastReceiver I'm doing the following

if(intent.getAction().equals("android.hardware.usb.action.USB_DEVICE_ATTACHED") {
    Intent launchIntent = new Intent(context, MainActivity.class);
    context.startActivity(launchIntent);
}

but it is not working.

I'm surely able to start the application if I'm putting the intent-filter and meta-data to the activity in the Manifest file. But that I don't wanna do because that starts the test activity.

How do I make this work?

Such that whenever I connect some hardware to my mobile then my application starts automatically from the Broadcast Receiver.

0

There are 0 answers