androidbroadcastreceiverandroid-pendingintentandroid-anr-dialog

android - Broadcast of Intent Has extras error


I have a broadcast receiver that detects when a USB device is attached/detached. The app opens when the device is connected however when i disconnect/connect the device to my android multiple times, i get the following ANR error: Does anyone know what is causing this? ANR error

Here is my Broadcast Receiver code:

    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();
        }
    }
}

Solution

  • It looks like your broadcast receiver is not the problem. The problem is that you've got code running on your main (UI) thread that is blocking the main (UI) thread. When Android tries to call your broadcast receiver's onReceive(), the call is blocked by something else and that is what is causing the ANR. What you are seeing is a symptom and not the actual cause of the problem.