我正在使用Android的应用程序,我正在使用Surface来读取QR码。使用Monitor检查资源我看到内存的常量增量从~7 MB到~20 MB,然后内存被释放并且行为重新开始。我想知道这是不正常还是我错过了什么。
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
TextView barCodeInfo;
SurfaceView cameraSurface;
Button scan;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
static final int REQUEST_CAMERA_PERMISSION = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraSurface = (SurfaceView) findViewById(R.id.cameraSurface);
barCodeInfo = (TextView) findViewById(R.id.barCodeResult);
scan = (Button) findViewById(R.id.scan);
scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
} else {
showCameraPreview();
}
}
});
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
@Override
public void release() {
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barCodes = detections.getDetectedItems();
if (barCodes.size() != 0) {
barCodeInfo.post(new Runnable() { // Use the post method of the TextView
public void run() {
barCodeInfo.setText( // Update the TextView
barCodes.valueAt(0).displayValue
);
}
});
}
}
});
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(200, 200)
.build();
cameraSurface.getHolder().addCallback(this);
}
private void showCameraPreview() {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSource.start(cameraSurface.getHolder());
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(cameraSurface != null){
cameraSurface = null;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showCameraPreview();
} else {
Toast.makeText(this, "Camera permission was denied", Toast.LENGTH_LONG).show();
}
}
}
仅在关闭应用程序时才恢复内存。