impementation of tuch to focus on camera in androi

2019-08-11 23:54发布

问题:

I want to implement touch to focus on my custom camera here is my code for custom camera . I know android api 14 level support focus and its also hardware dependent so any one have idea how to implement it.

    private SurfaceView previewSv;
    private ImageButton stillImgCamIb, videoCamIb, galleryIb;
    private TextView cancelTv;

    private Handler handler = new Handler();

    private Camera camera;
    private int cameraId = 0;
    private boolean cameraFlash = true;

    @Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    boolean hasCameraFlash = getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA_FLASH);
    boolean hasFrontCam = getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA_FRONT);

    previewSv = (SurfaceView) findViewById(R.id.preview_sv);

    stillImgCamIb = (ImageButton) findViewById(R.id.still_img_camera_ib);
    videoCamIb = (ImageButton) findViewById(R.id.video_camera_ib);
    galleryIb = (ImageButton) findViewById(R.id.gallery_ib);

    cancelTv = (TextView) findViewById(R.id.cancel_tv);

    stillImgCamIb.setOnClickListener(this);
    videoCamIb.setOnClickListener(this);
    galleryIb.setOnClickListener(this);
    cancelTv.setOnClickListener(this);

    startCameraPreview();
}

@Override
protected void onStop() {
    super.onStop();
    stopCameraPreview();
    stopRecording();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.still_img_camera_ib:
        if (mode == Mode.STILL_CAMERA) {
            if (previewing) {
                handleStillCamClick();
            }
        } else if (mode == Mode.VIDEO_CAMERA) {
            stopCameraPreview();
            startRecording();
            activateMode(Mode.RECORDING);
        } else if (mode == Mode.RECORDING) {
            stopRecording();
            activateMode(Mode.VIDEO_CAMERA);
        } else {
            activateMode(Mode.STILL_CAMERA);
        }
        break;
    case R.id.video_camera_ib:
        if (mode == Mode.VIDEO_CAMERA) {
            activateMode(Mode.STILL_CAMERA);
        } else {
            activateMode(Mode.VIDEO_CAMERA);
        }
        break;
    case R.id.gallery_ib:
        // openGallery();
        break;
    case R.id.cancel_tv:
        activateMode(Mode.VIDEO_CAMERA);
        stopRecording();
        break;

    default:
        break;
    }
}

private Uri capturedImageUri;
private boolean previewing = false;

private void startCameraPreview() {
    if (!previewing) {
        previewing = true;
        camera = Camera.open(cameraId);
        camera.getParameters().setFlashMode(
                cameraFlash ? Parameters.FLASH_MODE_ON
                        : Parameters.FLASH_MODE_OFF);
        camera.setDisplayOrientation(90);
        if (camera != null) {
            try {
                System.out.println("Started camera preview!");
                camera.setPreviewDisplay(previewSv.getHolder());
                camera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    previewSv.getHolder().addCallback(new Callback() {

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            stopCameraPreview();
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {

        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format,
                int width, int height) {
            if (previewing) {
                stopCameraPreview();
            }
            startCameraPreview();
        }
    });
}

private void stopCameraPreview() {
    if (camera != null && previewing) {
        camera.stopPreview();
        camera.release();
        camera = null;
        previewing = false;
    }
}

private void handleStillCamClick() {
    if (camera != null) {

        Parameters params = camera.getParameters();

        Size defaultSize = params.getPictureSize();
        System.out.println("Default size X:" + defaultSize.width + ", Y:"
                + defaultSize.height);

        // Loop over supported sizes and pick one that is larger than 640px
        // wide & tall, only if the default size is too small
        if (defaultSize.width < 640 || defaultSize.height < 640) {
            List<Size> sizes = params.getSupportedPictureSizes();

            // int biggestH = 0;
            // int biggestW = 0;
            int maxH = Integer.MAX_VALUE;
            int maxW = Integer.MAX_VALUE;
            for (int i = 0; i < sizes.size(); i++) {
                Size thisSize = sizes.get(i);

                int thisW = thisSize.width;
                int thisH = thisSize.height;

                boolean betterWidth = thisW < maxW && thisW >= 1000;
                boolean betterHeight = thisH < maxH && thisH >= 1000;
                boolean isFourThreeAspect = thisW == (4 * thisH / 3);

                if (isFourThreeAspect) {
                    System.out.println("Supports size: W" + thisSize.width
                            + ", H:" + thisSize.height);
                } else {
                    System.out.println("not 4/3, but Supports size: W"
                            + thisSize.width + ", H:" + thisSize.height);
                }

                if (betterWidth && betterHeight && isFourThreeAspect) {
                    maxH = thisH;
                    maxW = thisW;
                }

            }

            if (maxH < 99999 && maxW < 99999) {
                System.out.println("Found best size, W:" + maxW + ", H:"
                        + maxH);
                Toast.makeText(
                        this,
                        "Taking picture at resolution:" + maxW + "x" + maxH,
                        Toast.LENGTH_LONG).show();
                params.setPictureSize(maxW, maxH);
            } else {
                System.out
                        .println("Couldn't find best size! Going with default");
            }

            camera.setParameters(params);
        } else {

        }

        camera.takePicture(new ShutterCallback() {
            @Override
            public void onShutter() {
            }
        }, null, new PictureCallback() {
            public void onPictureTaken(byte[] bytes, Camera camera) {
                System.out
                        .println("got jpeg bytes, length:" + bytes.length);
                stopCameraPreview();
            }
        });
    }
}

public MediaRecorder mediaRecorder = new MediaRecorder();
private boolean recording = false;

protected void startRecording() {
    String path = Environment.getExternalStorageDirectory()
            .getAbsolutePath().toString();
    String filename = "/xyz.mp4";

    mediaRecorder = new MediaRecorder();

    camera = Camera.open(cameraId);
    camera.getParameters().setFlashMode(
            cameraFlash ? Parameters.FLASH_MODE_AUTO
                    : Parameters.FLASH_MODE_OFF);
    camera.setDisplayOrientation(90);
    Log.d("TabCustomCameraFragment", "startRecording - Camera.open");
    camera.lock();
    camera.unlock();

    mediaRecorder.setCamera(camera);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    mediaRecorder.setProfile(CamcorderProfile
            .get(CamcorderProfile.QUALITY_HIGH));
    mediaRecorder.setVideoSize(640, 640);

    mediaRecorder.setPreviewDisplay(previewSv.getHolder().getSurface());
    mediaRecorder.setOutputFile(path + filename);
    if (isVertical()) {
        mediaRecorder.setOrientationHint(cameraId == 0 ? 90 : 270);
    } else {
        mediaRecorder.setOrientationHint(cameraId == 0 ? 90 : 180);
    }
    mediaRecorder.setMaxDuration(10000);

    try {
        camera.stopPreview();

        mediaRecorder.prepare();
        mediaRecorder.start();
        recording = true;
        remainingCaptureTime = MAX_VIDEO_DURATION;
        updateRemainingTime();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

protected void stopRecording() {
    if (mediaRecorder != null && recording) {
        mediaRecorder.stop();
        mediaRecorder.reset();
        mediaRecorder.release();
        camera.release();
        recording = false;
        handler.removeCallbacksAndMessages(null);
    }
}

private int remainingCaptureTime;

private void updateRemainingTime() {
    Log.d("TabCustomCameraFragment",
            "updateRemainingTime - remainingCaptureTime="
                    + remainingCaptureTime);
    if (remainingCaptureTime <= 500) {
        stopCameraPreview();
        stopRecording();
        return;
    }

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            remainingCaptureTime -= 500;
            updateRemainingTime();
        }
    }, 500);
}

private boolean isVertical() {
    Display getOrient = getWindowManager().getDefaultDisplay();
    if (getOrient.getWidth() <= getOrient.getHeight()) {
        return true;
    }
    return false;
}

private enum Mode {
    STILL_CAMERA, VIDEO_CAMERA, RECORDING;
}

private Mode mode = Mode.STILL_CAMERA;

private void activateMode(Mode mode) {
    switch (mode) {
    case STILL_CAMERA:
        this.mode = Mode.STILL_CAMERA;
        cancelTv.setVisibility(View.GONE);
        galleryIb.setVisibility(View.VISIBLE);
        videoCamIb.setVisibility(View.VISIBLE);
        break;
    case VIDEO_CAMERA:
        this.mode = Mode.VIDEO_CAMERA;
        stillImgCamIb.setImageResource(R.drawable.ic_launcher);
        videoCamIb.setImageResource(R.drawable.ic_launcher);
        cancelTv.setVisibility(View.GONE);
        galleryIb.setVisibility(View.VISIBLE);
        videoCamIb.setVisibility(View.VISIBLE);
        break;
    case RECORDING:
        this.mode = Mode.RECORDING;
        stillImgCamIb.setImageResource(R.drawable.ic_launcher);
        cancelTv.setVisibility(View.VISIBLE);
        galleryIb.setVisibility(View.GONE);
        videoCamIb.setVisibility(View.GONE);
        break;

    default:
        break;
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    stopCameraPreview();
    stopRecording();
}