To Add try-catch for MetadataChangedListener to handle the Exception

Since the BT is not enabled, the BluetoothAdapter can't register
the device into Metadata List. Then, the BluetoothAdapter throws the
execption while the UI did the unregister.

Bug: 291207069
Test: build pass
Change-Id: I86e0a3369d7371747a249b34f949d59929afb1c7
This commit is contained in:
SongFerngWang
2023-08-30 19:49:29 +08:00
committed by SongFerng Wang
parent 7f72bcf667
commit d140634164
2 changed files with 78 additions and 12 deletions

View File

@@ -167,6 +167,10 @@ public class AdvancedBluetoothDetailsHeaderController extends BasePreferenceCont
}
private void registerBluetoothDevice() {
if (mBluetoothAdapter == null) {
Log.d(TAG, "No mBluetoothAdapter");
return;
}
if (mBluetoothDevices == null) {
mBluetoothDevices = new HashSet<>();
}
@@ -180,23 +184,52 @@ public class AdvancedBluetoothDetailsHeaderController extends BasePreferenceCont
}
});
if (mBluetoothDevices.isEmpty()) {
Log.d(TAG, "No BT devcie to register.");
Log.d(TAG, "No BT device to register.");
return;
}
mCachedDevice.registerCallback(this);
mBluetoothDevices.forEach(bd ->
mBluetoothAdapter.addOnMetadataChangedListener(bd,
mContext.getMainExecutor(), mMetadataListener));
Set<BluetoothDevice> errorDevices = new HashSet<>();
mBluetoothDevices.forEach(bd -> {
try {
boolean isSuccess = mBluetoothAdapter.addOnMetadataChangedListener(bd,
mContext.getMainExecutor(), mMetadataListener);
if (!isSuccess) {
Log.e(TAG, bd.getAnonymizedAddress() + ": add into Listener failed");
errorDevices.add(bd);
}
} catch (NullPointerException e) {
errorDevices.add(bd);
Log.e(TAG, bd.getAnonymizedAddress() + ":" + e.toString());
} catch (IllegalArgumentException e) {
errorDevices.add(bd);
Log.e(TAG, bd.getAnonymizedAddress() + ":" + e.toString());
}
});
for (BluetoothDevice errorDevice : errorDevices) {
mBluetoothDevices.remove(errorDevice);
Log.d(TAG, "mBluetoothDevices remove " + errorDevice.getAnonymizedAddress());
}
}
private void unRegisterBluetoothDevice() {
if (mBluetoothAdapter == null) {
Log.d(TAG, "No mBluetoothAdapter");
return;
}
if (mBluetoothDevices == null || mBluetoothDevices.isEmpty()) {
Log.d(TAG, "No BT devcie to unregister.");
Log.d(TAG, "No BT device to unregister.");
return;
}
mCachedDevice.unregisterCallback(this);
mBluetoothDevices.forEach(bd -> mBluetoothAdapter.removeOnMetadataChangedListener(bd,
mMetadataListener));
mBluetoothDevices.forEach(bd -> {
try {
mBluetoothAdapter.removeOnMetadataChangedListener(bd, mMetadataListener);
} catch (NullPointerException e) {
Log.e(TAG, bd.getAnonymizedAddress() + ":" + e.toString());
} catch (IllegalArgumentException e) {
Log.e(TAG, bd.getAnonymizedAddress() + ":" + e.toString());
}
});
mBluetoothDevices.clear();
}