I am reading this page about how to program Android to talk to a USB accessory. One of the steps involves registering a BroadcastReceiver
to obtain permission from the user:
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
where mUsbReceiver
is defined 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 is why synchronized (this)
is used? onReceive()
will be called on the UI thread and that's it. This block of code does not seem to touch any data which may be accessed by other threads, unless the object accessory
counts (and there's nothing on the page that suggests it is).
I searched on the web, and there does not seem to be much emphasis on thread-safety in onReceive()
(it's called by a very specific thread after all). Am I missing something?
Update: I want to stress that I know what synchronized (this)
does, because some comments below seem to suggest I don't. What I don't understand is why it was used in the above code fragment, which seems unnecessary.