我想在相同的Activity中停止后重启相机源
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我想在相同的Activity中停止后重启相机源相关的知识,希望对你有一定的参考价值。
我为条形码检测器做了一个应用,所以我使用SurfaceView来处理相机源。相机检测到条形码并返回其值后,我将其停止。没有任何功能可以在任何事件上重新启动摄像机源和表面视图,只需要一个功能,即camersource.start();
它启动但它在后台工作的问题,我什么都看不到如何解决这个问题?并再次显示surfaceview和相机源。
这是活动onCreate方法的完整代码
@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();
答案
捕获代码后,您可能会停止摄像头源并再次重新启动OnCreate方法。或者您可以使用Intent再次调用活动,如:
Intent intent= new Intent (getBaseContext,MainActivity.class); // your activity
startActivity(intent);
另一答案
要在cameraSource.stop()之后重启,你需要:
cameraSource.start(surfaceView.getHolder());
以上是关于我想在相同的Activity中停止后重启相机源的主要内容,如果未能解决你的问题,请参考以下文章