Prevent USB_DEVICE_ATTACHED launching app after a

2019-08-11 15:11发布

问题:

I have an activity listening for the USB_DEVICE_ATTACHED broadcast intent, which launches when the user plugs in my USB device and selects our app. My problem is the android host devices reboot themselves once a day (usually around 4am), at which point the attached USB_DEVICE_ATTACHED intent is also fired by itself.

In this circumstance, I definitely don't want to launch my activity as it doesn't know how to close itself. How can I prevent that from happening? I tried to use the PowerManager.isScreenOn() boolean to not launch my activity (target is API 17), but it thinks the screen is indeed on.

 PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        if (powerManager.isInteractive()) {
            startActivity(intent);
        }
    }
    else{
        //noinspection deprecation
        if (powerManager.isScreenOn()) {
            startActivity(intent);
        }
    }

回答1:

I don't think you have enough information to determine if the USB_DEVICE_ATTACHED broadcast is due to your user plugging something in, or the device rebooting itself.

What I would do is launch the Activity in any case and have the Activity close itself if the user hasn't performed any action within a certain period of time (1 minute or 10 minutes or whatever).