1

I know that I can use USB host mode with this manifest configuration:

<activity
    android:name="com.mypackage.MyActivity"
    android:label="@string/app_name">

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

</activity>

And this will launch my activity every time a USB device is connected. The problem is that I don't want it to reopen if it is already running in foreground. I also don't want it to start if any other of the activities of my app is already running in foreground. How to do that?

manfcas
  • 1,933
  • 7
  • 28
  • 47

1 Answers1

1

I finally found the way to go. I've added in my manifest a new receiver:

<receiver android:name=".content.UsbReceiver">

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

which handles the event in this way:

public class UsbReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!CustomApplication.resumed) {
            Context applicationContext = context.getApplicationContext();
            Intent startIntent = new Intent(applicationContext, MyActivity.class);
            startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            applicationContext.startActivity(startIntent);
        }
    }

}

where resumed is a static field in my custom Application class:

public class CustomApplication extends Application {

    public static boolean resumed = false;

}

I set the value of this field in the parent class of all my activities:

public abstract class AbstractActivity extends Activity {

    @Override
    protected void onResume() {
        super.onResume();
        CustomApplication.resumed = true;
    }

    @Override
    protected void onPause() {
        CustomApplication.resumed = false;
        super.onPause();
    }

}

In this way I actually launch MyActivity only if none of my activities is already in foreground.

manfcas
  • 1,933
  • 7
  • 28
  • 47