android - 意图广播有额外错误

android - Broadcast of Intent Has extras error

我有一个广播接收器可以检测 USB 设备何时 attached/detached。该应用程序在设备连接时打开,但是当我 disconnect/connect 设备多次连接到我的 android 时,我收到以下 ANR 错误:有人知道是什么原因造成的吗? ANR error

这是我的广播接收器代码:

    String USB_TAG = "USB_TAG";
    String BROADCAST_TAG = "BROADCAST_TAG";
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(BROADCAST_TAG, "BroadcastReceiver Event");
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            Log.d(BROADCAST_TAG, "BroadcastReceiver DEVICE ATTACHED");
            Toast.makeText(context, "Device Detected", Toast.LENGTH_SHORT).show();
            new Thread(() -> {
                try {
                    if(MainActivity.eMRO_Backend != null) {
                        if (MainActivity.eMRO_Backend.threadsClosed) {
                            MainActivity.eMRO_Backend = new eMRO_Backend(context);
                        }
                    }
                } catch (Exception e){
                    Log.d(BROADCAST_TAG, "BroadcastReceiver attach ex: " + e.getMessage());
                }
            }).start();
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {  
            Toast.makeText(context, "Device Not Detected", Toast.LENGTH_SHORT).show();
            new Thread(() -> {
                Looper.prepare();
                try {
                    MainActivity.powerStatusQueue.put(false);
                    MainActivity.laserKeyStatusQueue.put(false);
                    if(MainActivity.eMRO_Backend != null)
                        MainActivity.eMRO_Backend.shutDownThreads();
                } catch (Exception e) {
                    Log.d(BROADCAST_TAG, "BroadcastReceiver detach ex: " + e.getMessage());
                }

            }).start();
        }
    }
}

看来你的广播接收器没有问题。问题是您的主 (UI) 线程上的代码 运行 阻塞了主 (UI) 线程。当 Android 试图呼叫您的广播接收器的 onReceive() 时,呼叫被其他东西阻止,这就是导致 ANR 的原因。您看到的是症状,而不是问题的实际原因