The first code snippet indeed looks better than the duplicated statements.
You could also implement a separate helper method with vararg and then invoke it with arbitrary number of arguments:
public void unregisterReceivers(BroadcastReceiver ... receivers) {
for (BroadcastReceiver br : receivers)
if (br != null) {
try {
unregisterReceiver(br);
} catch (Exception ignored) {
// at least log exception that some receiver failed to unregister
}
}
}
}
unregisterReceivers(receiverA, receiverB, receiverC);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…