import android.content.Context;
import android.content.Intent;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.media.Image;
import android.media.ImageReader;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageButton;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;



public class MainActivity extends AppCompatActivity {

private TextureView iTextureView;
private CameraDevice iCameraDevice;

private HandlerThread iBackgroundHandlerThread;
private Handler iBackgroundHandler;
private ImageReader iImageReader;

private CameraCaptureSession iPreviewCaptureSession;
private CaptureRequest.Builder iCaptureRequestBuilder;
private ImageButton foto;

private File iImageFolder;
private String iImageFile;


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

createImageFolder();

iTextureView = (TextureView) findViewById(R.id.textureView);
foto = (ImageButton) findViewById(R.id.cameraImageButton2);





foto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {iPreviewCaptureSession.capture(iCaptureRequestBuilder.build(), iPreviewCaptureCallback, null); }
catch (CameraAccessException e) { e.printStackTrace(); }
} }); }




private TextureView.SurfaceTextureListener iSurfaceTextureListener =
new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
iImageReader = ImageReader.newInstance(1920,1080, ImageFormat.JPEG, 1);
iImageReader.setOnImageAvailableListener(iOnImageAvailableListener,null);
connectCamera();}

@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { }
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {}};






private CameraDevice.StateCallback iCameraDeviceStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {iCameraDevice = camera; startPreview(); }

@Override
public void onDisconnected(CameraDevice camera) { camera.close(); iCameraDevice = null; }

@Override
public void onError(CameraDevice camera, int error) {camera.close(); iCameraDevice = null; }
};






private final ImageReader.OnImageAvailableListener iOnImageAvailableListener = new
ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
iBackgroundHandler.post(new ImageSaver(reader.acquireLatestImage()));} };



private class ImageSaver implements Runnable {

private final Image iImage;

public ImageSaver(Image image) { iImage = image; }

@Override
public void run() {
ByteBuffer byteBuffer = iImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);

FileOutputStream fileOutputStream = null;

try {fileOutputStream = new FileOutputStream(iImageFile);
fileOutputStream.write(bytes); }

catch (IOException e) { e.printStackTrace(); }

finally {
iImage.close();

Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaStoreUpdateIntent.setData(Uri.fromFile(new File(iImageFile)));
sendBroadcast(mediaStoreUpdateIntent);

if(fileOutputStream != null) {try {fileOutputStream.close();}
catch (IOException e) { e.printStackTrace(); }}}}}






private CameraCaptureSession.CaptureCallback iPreviewCaptureCallback = new
CameraCaptureSession.CaptureCallback() {

@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);

try {
iCaptureRequestBuilder.addTarget(iImageReader.getSurface());
iPreviewCaptureSession.capture(iCaptureRequestBuilder.build(), run2, null);

} catch (CameraAccessException e) { e.printStackTrace(); }

}
};









@Override
protected void onResume() {
super.onResume();

startBackgroundThread();

if(iTextureView.isAvailable()) {

connectCamera();
} else {
iTextureView.setSurfaceTextureListener(iSurfaceTextureListener);
}
}

private void connectCamera() {
CameraManager cameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);

try { ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
cameraManager.openCamera("0", iCameraDeviceStateCallback, null);}
catch (CameraAccessException e) { e.printStackTrace(); }}






CameraCaptureSession.StateCallback run = new CameraCaptureSession.StateCallback(){

@Override
public void onConfigured(CameraCaptureSession session) {

iPreviewCaptureSession = session;
try {iPreviewCaptureSession.setRepeatingRequest(iCaptureRequestBuilder.build(),null, null);}
catch (CameraAccessException e) {e.printStackTrace();}}

@Override
public void onConfigureFailed(CameraCaptureSession session) {} };






CameraCaptureSession.CaptureCallback run2 = new
CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request, long timestamp, long frameNumber) {

super.onCaptureStarted(session, request, timestamp, frameNumber);

try {createImageFileName();}
catch (IOException e) { e.printStackTrace(); } } };





private void startPreview() {
SurfaceTexture surfaceTexture = iTextureView.getSurfaceTexture();
surfaceTexture.setDefaultBufferSize(1920,1080);
Surface previewSurface = new Surface(surfaceTexture);

try {
iCaptureRequestBuilder = iCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
iCaptureRequestBuilder.addTarget(previewSurface);
iCameraDevice.createCaptureSession(Arrays.asList(previewSurface,iImageReader.getSurface()),run, null);}

catch (CameraAccessException e) {e.printStackTrace();}}




private void startBackgroundThread() {
iBackgroundHandlerThread = new HandlerThread("Camera2Foto");
iBackgroundHandlerThread.start();
iBackgroundHandler = new Handler(iBackgroundHandlerThread.getLooper()); }


private void createImageFolder() {
File imageFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
iImageFolder = new File(imageFile, "Camera2Foto");
if(!iImageFolder.exists()) {
iImageFolder.mkdirs(); } }



private File createImageFileName() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "IMAGE_" + timestamp + "_";
File imageFile = File.createTempFile(prepend, ".jpg", iImageFolder);
iImageFile = imageFile.getAbsolutePath();
return imageFile; }


} return imageFile; }