1
0

android: don't keep adding BarcodeScannerView instances to contentFrame when starting camera

When putting app to background with qr scanner active, then moved to foreground again,
SimpleScannerActivity instance is not destroyed, but the local mScannerView was re-initialized
with a new instance (through startCamera()) regardless of pre-existing instance, and added to
the contentFrame. This leaves the previous mScannerView instance in limbo, potentially getting
garbage collected at unpredictable times.
This commit is contained in:
Sander van Grieken
2025-07-22 09:42:15 +02:00
parent 8eb3c43603
commit 3947733d9f

View File

@@ -88,17 +88,19 @@ public class SimpleScannerActivity extends Activity {
} }
private void startCamera() { private void startCamera() {
mScannerView = new BarcodeScannerView(this); if (mScannerView == null) {
mScannerView.setCropRatio(0.75f); // Set crop ratio to 75% (this defines the square area shown in the scanner view) mScannerView = new BarcodeScannerView(this);
// by default only Format.QR_CODE is set mScannerView.setCropRatio(0.75f); // Set crop ratio to 75% (this defines the square area shown in the scanner view)
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame); // by default only Format.QR_CODE is set
contentFrame.addView(mScannerView); ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView.setOnBarcodeListener(result -> { contentFrame.addView(mScannerView);
// Handle the scan result mScannerView.setOnBarcodeListener(result -> {
this.setResultAndClose(result.getText()); // Handle the scan result
// Return false to stop scanning after first result this.setResultAndClose(result.getText());
return false; // Return false to stop scanning after first result
}); return false;
});
}
mScannerView.openAsync(); // Start camera on resume mScannerView.openAsync(); // Start camera on resume
} }