Synchronized block inside onReceive () callback

I am reading this page on how to program Android on a USB accessory. One of the steps involves registering BroadcastReceiverto obtain permission from the user:

IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);

where is mUsbReceiverdefined as:

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);

                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if(accessory != null){
                        //call method to set up accessory communication
                    }
                }
                else {
                    Log.d(TAG, "permission denied for accessory " + accessory);
                }
            }
        }
    }
};

What puzzles me, why is it used synchronized (this)? onReceive()will be called in the user interface thread and that it is. This block of code does not seem to apply to any data that other threads can access unless the object accessorycounts (and there is nothing on its page).

I searched on the Internet, and it seems that not much attention is paid to thread safety in onReceive()(after all, it is called a very specific thread). Did I miss something?

: , , synchronized (this), . , , .

+4
1

onReceive() . BroadcastReceiver registerReceiver(), Handler scheduler, onReceive() , . docs:

Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

, , . - , , Intent. null, .

, , , - synchronized, BroadcastReceiver registerReceiver(BroadcastReceiver, IntentFilter), onReceive() .

, , , onReceive(), . synchronized, , onReceive() , .

0

Source: https://habr.com/ru/post/1694102/


All Articles