简体   繁体   English

如何使用相同的按钮启动和停止方法

[英]How to start and stop method with same button

How would one go about starting and stopping this camera (or preview?) with the same onClick button?如何使用相同的 onClick 按钮启动和停止此相机(或预览?)? Starting the camera was no issue, but now also closing the camera, with the same button is proving to be more difficult for a newbie like me.启动相机没有问题,但现在也关闭相机,对于像我这样的新手来说,使用相同的按钮被证明更困难。

When pressing the button a second time, the program crashes now, which is not ideal.第二次按下按钮时,程序现在崩溃了,这并不理想。

public class MainActivity extends AppCompatActivity {

PreviewView previewView;
public int REQUEST_CODE_PERMISSIONS = 101;
public final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    previewView = findViewById(R.id.previewView);
    Button captureButton = findViewById(R.id.buttonPreview);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          if (allPermissionsGranted()) {
              startCamera();
          } else {
              ActivityCompat.requestPermissions(MainActivity.this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
          }
      }
      });
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull 
int[] grantResults) {
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  if (allPermissionsGranted()) {
      startCamera();
  } else {
      Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
      finish();
  }
}

public boolean allPermissionsGranted() {

  for (String permission : REQUIRED_PERMISSIONS) {
      if (ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED) {
          return false;
      }
  }
  return true;
}
 public void startCamera() {
    ListenableFuture cameraProviderFuture = ProcessCameraProvider.getInstance(this);

    cameraProviderFuture.addListener(() -> {
        try {
            ProcessCameraProvider cameraProvider = (ProcessCameraProvider) cameraProviderFuture.get();
            Preview preview = new Preview.Builder().build();
            CameraSelector cameraSelector = new CameraSelector.Builder()
                    .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                    .build();
            ImageAnalysis imageAnalysis =
                    new ImageAnalysis.Builder()
                            .setTargetResolution(new Size(1280, 720))
                            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                            .build();
            preview.setSurfaceProvider(previewView.getSurfaceProvider());
            Camera camera = cameraProvider.bindToLifecycle(
                    ((LifecycleOwner) this),
                    cameraSelector,
                    preview,
                    imageAnalysis);

        } catch (InterruptedException | ExecutionException e) {

        }
    }, ContextCompat.getMainExecutor(this));
}
}

Just need to create a boolean or int variable such as:只需要创建一个 boolean 或 int 变量,例如:

boolean ifCameraStarted=false;

When your called startCamera() you change this variable to true,and when you stopcamera change it to false;当您调用 startCamera() 时,您将此变量更改为 true,当您停止相机时将其更改为 false; When you click the button,you judge with this variable if it is true or false and do different things当你点击按钮时,你用这个变量判断它是真还是假,做不同的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM