我正在使用 google vision api 构建一个具有 qr 扫描仪的应用程序。读取二维码后,我无法停止相机。流程是MainActivity -> QrActivity
一旦二维码收到检测,应用程序应该返回到主要活动。
如果我不称cameraSource.release()
它工作正常,但设备会发热很多并且对电池消耗有重大影响。但是,如果我释放相机源 mainActivity 变得无响应并且应用程序将崩溃。
为什么会变得反应迟钝?以及释放相机源的正确位置在哪里?
QrActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr);
cancelBtn = (Button) findViewById(R.id.cancel_button);
cancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
new QrReader(this);
}
QrReader 类
public class QrReader {
private static final String TAG = "QrReader";
private SurfaceView cameraView;
private TextView barcodeInfo;
private BarcodeDetector barcodeDetector;
private CameraSource cameraSource;
private Activity mActivity;
private AccessPointCredentials barCodeData;
public QrReader(Activity activity) {
this.mActivity = activity;
cameraView = (SurfaceView) mActivity.findViewById(R.id.camera_view);
barcodeInfo = (TextView) mActivity.findViewById(R.id.code_info);
barcodeDetector =
new BarcodeDetector.Builder(mActivity)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(mActivity, barcodeDetector)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
cameraSource = new CameraSource
.Builder(mActivity, barcodeDetector)
.setAutoFocusEnabled(true)
.setFacing(0)
.build();
try {
cameraSource.start(cameraView.getHolder());
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Log.i(TAG, "surfaceDestroyed: stopping camera Source");
// cameraSource.release();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
@Override
public void release() {
Log.i(TAG, "release: ");
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barCodes = detections.getDetectedItems();
if (barCodes.size() != 0) {
Log.i(TAG, "received a Barcode");
barcodeInfo.post(new Runnable() { // Use the post method of the TextView
public void run() {
barcodeInfo.setText(barCodes.valueAt(0).displayValue);
}
});
Gson g = new Gson();
try {
barCodeData = g.fromJson(barCodes.valueAt(0).rawValue, AccessPointCredentials.class);
} catch (Exception e) {
barCodeData = new AccessPointCredentials();
barCodeData.setSsid(barCodes.valueAt(0).rawValue);
barCodeData.setPass(null);
e.printStackTrace();
}
connectToWifi(barCodeData);
// CameraSource.release causes app to freeze
// cameraSource.release();
}
}
});
}
private void connectToWifi(final AccessPointCredentials credentials) {
//wificonnect code
}
}