<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
尝试从这个问题FirstActivity
中的“删除”意图过滤器
更新
FirstActivity 在每个USB_DEVICE_ATTACHED
(甚至SecondActivity
正在运行)上触发,因为您在文件<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
中为它设置了过滤器。AndroidManifest.xml
所以你应该在SecondActivity
运行时禁用这个过滤器。你可以这样做:
1)添加(例如AliasFirstActivity
)AndroidManifest.xml
到您的FirstActivity
并将<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
过滤器移动到别名描述(您应该<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
从FirstActivity
描述中删除),如下所示:
<activity-alias
android:targetActivity=".FirstActivity"
android:name=".AliasFirstActivity"
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>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</activity-alias>
2)将此代码添加到onCreate()
(或onResume()
)SecondActivity
PackageManager pm = getApplicationContext().getPackageManager();
ComponentName compName =
new ComponentName(getPackageName(), getPackageName() + ".AliasFirstActivity");
pm.setComponentEnabledSetting(
compName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
抑制意图过滤USB_DEVICE_ATTACHED
器FirstActivity
。你应该有这样的SecondActivity
东西:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
triggerReceiver = new TriggerReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(triggerReceiver, filter);
PackageManager pm = getApplicationContext().getPackageManager();
ComponentName compName =
new ComponentName(getPackageName(), getPackageName() + ".AliasFirstActivity");
pm.setComponentEnabledSetting(
compName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
那应该可以解决您的问题。3)如果需要,您可以使用以下代码恢复in (或 in )的<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
过滤器:FirstActivity
onDestroy()
onPause()
SecondActivity
PackageManager pm = getApplicationContext().getPackageManager();
ComponentName compName =
new ComponentName(getPackageName(), getPackageName() + ".AliasFirstActivity");
pm.setComponentEnabledSetting(
compName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);