我为条形码检测器做了一个应用,所以我使用SurfaceView来处理相机源。相机检测到条形码并返回其值后,我将其停止。没有任何功能可以在任何事件上重新启动摄像机源和表面视图只有一个功能是camersource.start();
它启动但问题在后台运行,我无法看到如何解决这个问题?并再次显示surfaceview和相机源。
这是活动onCreate Method
的整个代码 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.cameraPreview);
txtShow = (TextView) findViewById(R.id.txtShow);
startBarcode();
}
public void startBarcode() {
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(800, 600)
.setAutoFocusEnabled(true)
.build();
//Events
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
@Override
public void release() {
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
txtShow.post(new Runnable() {
@Override
public void run() {
//create vibrate
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
//set result for Text View
txtShow.setText(qrCodes.valueAt(0).displayValue);
// surfaceView.setTop(200);
cameraSource.stop();
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.barcode);
mp.start();
答案 0 :(得分:2)
在cameraSource.stop()之后重启你需要:
cameraSource.start(surfaceView.getHolder());
答案 1 :(得分:1)
捕获代码后,您可以停止摄像头源并再次重新启动OnCreate方法。或者你可以使用Intent再次调用活动:
Intent intent= new Intent (getBaseContext,MainActivity.class); // your activity
startActivity(intent);