Android应用切换USB设备时重启问题:如何实现期望行为
解决USB设备切换导致Android应用重启的问题
问题根源
你当前把USB_DEVICE_ATTACHED的Intent过滤器绑定在主Activity上,而默认的standard启动模式下,系统每次收到该Intent都会创建新的Activity实例,甚至触发应用重启。要实现你的需求,需要调整Activity启动模式并处理新Intent的回调。
具体解决方案
1. 修改Activity的启动模式
在Manifest的主Activity标签中添加android:launchMode="singleTask",确保Activity始终只有一个实例,收到新Intent时不会重建:
<application> ... <activity android:name=".YourMainActivity" android:launchMode="singleTask"> <!-- 新增启动模式配置 --> ... <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> </application>
2. 重写onNewIntent方法处理设备连接
在你的主Activity中重写onNewIntent方法,接收USB设备连接的Intent并处理,避免应用重启:
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 更新当前Intent,确保后续获取的是最新的设备连接信息 setIntent(intent); // 校验是否为USB设备连接的Intent if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) { // 获取连接的USB设备实例 UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null) { // 这里执行你的设备连接逻辑,比如初始化串口、发送本地通知等 handleNewUsbDevice(device); } } } // 示例:处理新连接的USB设备 private void handleNewUsbDevice(UsbDevice device) { // 发送本地通知告知用户设备已连接 NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("USB_CONNECT", "USB设备通知", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } Notification notification = new NotificationCompat.Builder(this, "USB_CONNECT") .setContentTitle("USB设备已连接") .setContentText("设备名称:" + device.getDeviceName()) .setSmallIcon(R.drawable.ic_usb_notify) .build(); notificationManager.notify(1001, notification); // 这里可以添加串口初始化等业务逻辑 }
效果验证
- 应用未运行时:连接USB设备,系统会直接启动你的主Activity,满足需求1。
- 应用已运行时:切换USB设备,系统会调用
onNewIntent方法,你可以在这个方法里处理新设备的连接逻辑,应用不会重启,满足需求2。
内容的提问来源于stack exchange,提问作者Sucper
相关产品推荐
相关产品推荐

