Android 当应用为 运行 时不启动 activity(在 IntentFilter 匹配上)

Android do not launch activity when app is running (on IntentFilter match)

我正在处理 USB 设备连接。这里我的 Android phone 将在 HOST 模式下工作。

我在清单中指定了 Intent 过滤器,例如:

    <activity android:name=".TestActivity">
    <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>

    <meta-data
        android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
        android:resource="@xml/device_filter" />
    </activity>

所以每当我的设备连接时,它都会显示 USB 权限的弹出窗口并启动 TestActivity。

但是如果我的应用程序是 运行 而我在其他 activity 中,那么它也会启动测试 activity。

在这里,如果我的应用程序已经 运行,我想避免再次启动 activity。 可能吗?

谢谢

USB_DEVICE_ATTACHED

使用BroadcastReceiver

并在 onReceive()

这里我有解决方法。 这里 Intent 注册到 activity 所以 activity 肯定会在硬件连接上启动 ( ie: on receive of this action <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />)

  1. Create activity without setting layout and add finish on create.if you want to get device detail then you can get from here.
onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    UsbDevice device = (UsbDevice)getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);
    finish();
}
  1. Manifest file add set theme for your activity (here TestActivity)

android:theme="@android:style/Theme.NoDisplay"