Cannot resolve imports of CameraDevice.java from android.hardware.camera2-package in Android Studio 3.2.1












0















I'm trying to implement a camera into my android-app, for which I'm using the android.hardware.camera2 package. I did manage to somehow open the camera on my device, however it won't take a picture, because the first if-statement in takePicture():



    if(null == cameraDevice) {
Log.e(TAG, "cameraDevice is null");
return;
}


apperently gets null for cameraDevice, according to my logcat.
I think, this happens because i did something wrong or Android Studio got something wrong with my dependencies.



dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-annotations:28.0.0'

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


While imports work fine for my own .java's, they "cannot resolve symbol.''"
in the imported CameraDevice.java (picture of the failing imports)
So, even though my project compiles with no errors, it doesn't work, because the imported CameraDevice can't import their imports properly.



import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.IntDef;
import android.annotation.SystemApi;
import static android.hardware.camera2.ICameraDeviceUser.NORMAL_MODE;
import static android.hardware.camera2.ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE;


I tried:



Clean & Rebuild



Invalidate Chaches/Restart



Deleting .gradle + .idea



using different versions of com.android.support:support-annotations



reinstalling AS



so far, with no success.



I had a similar problem with the JSON-package in the same project, which i couldn't resolve at all.



this is my code:



import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Toast;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class sleepingtime extends AppCompatActivity {
private static final String TAG = "sleepingtime";
private Handler mHandler = new Handler();
private TextureView textureView;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private String cameraId;
protected CameraDevice cameraDevice;
protected CameraCaptureSession cameraCaptureSessions;
protected CaptureRequest captureRequest;
protected CaptureRequest.Builder captureRequestBuilder;
private Size imageDimension;
private ImageReader imageReader;
private File file;
private static final int REQUEST_CAMERA_PERMISSION = 200;
private boolean mFlashSupported;
private Handler mBackgroundHandler;
private HandlerThread mBackgroundThread;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sleepingtime);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); //hide navbar
textureView = (TextureView) findViewById(R.id.textureView);
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
Log.i(TAG,"good Morning");

takePicture();
//goToMain(5000);
}

TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//open your camera here
openCamera();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Transform you image captured size according to the surface width and height
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
};

private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
//This is called when the camera is open
Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
@Override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
@Override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
createCameraPreview();
}
};
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void takePicture() {
if(null == cameraDevice) {
Log.e(TAG, "cameraDevice is null");
return;
}
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
Log.i(TAG, "Kammera: " + manager.getCameraIdList());
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size jpegSizes = null;
if (characteristics != null) {
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
}
int width = 640;
int height = 480;
if (jpegSizes != null && 0 < jpegSizes.length) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurfaces = new ArrayList<Surface>(2);
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
// Orientation
int rotation = getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
}
}
private void save(byte bytes) throws IOException {
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(bytes);
} finally {
if (null != output) {
output.close();
}
}
}
};
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
createCameraPreview();
}
};
cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession session) {
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(sleepingtime.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(sleepingtime.this, new String{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Log.e(TAG, "openCamera X");
}
protected void updatePreview() {
if(null == cameraDevice) {
Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions, @NonNull int grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// close the app
Toast.makeText(sleepingtime.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
finish();
}
}
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume");
startBackgroundThread();
if (textureView.isAvailable()) {
openCamera();
} else {
textureView.setSurfaceTextureListener(textureListener);
}
}
@Override
protected void onPause() {
Log.e(TAG, "onPause");
//closeCamera();
stopBackgroundThread();
super.onPause();
}



public void goToMain(int countdownms){
//countdownms entspricht der Zeit bis zum Seitenwechsel in ms
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
Intent intent = new Intent(sleepingtime.this, MainActivity.class);
startActivity(intent);
} catch(Exception e){
e.printStackTrace();
Log.i(TAG, "Error calling activity MainActivity " + e);
}
}
}, countdownms);

}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}

}


Thanks for your help!










share|improve this question



























    0















    I'm trying to implement a camera into my android-app, for which I'm using the android.hardware.camera2 package. I did manage to somehow open the camera on my device, however it won't take a picture, because the first if-statement in takePicture():



        if(null == cameraDevice) {
    Log.e(TAG, "cameraDevice is null");
    return;
    }


    apperently gets null for cameraDevice, according to my logcat.
    I think, this happens because i did something wrong or Android Studio got something wrong with my dependencies.



    dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:support-annotations:28.0.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    }


    While imports work fine for my own .java's, they "cannot resolve symbol.''"
    in the imported CameraDevice.java (picture of the failing imports)
    So, even though my project compiles with no errors, it doesn't work, because the imported CameraDevice can't import their imports properly.



    import android.annotation.NonNull;
    import android.annotation.Nullable;
    import android.annotation.IntDef;
    import android.annotation.SystemApi;
    import static android.hardware.camera2.ICameraDeviceUser.NORMAL_MODE;
    import static android.hardware.camera2.ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE;


    I tried:



    Clean & Rebuild



    Invalidate Chaches/Restart



    Deleting .gradle + .idea



    using different versions of com.android.support:support-annotations



    reinstalling AS



    so far, with no success.



    I had a similar problem with the JSON-package in the same project, which i couldn't resolve at all.



    this is my code:



    import android.Manifest;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.graphics.ImageFormat;
    import android.graphics.SurfaceTexture;
    import android.hardware.camera2.CameraAccessException;
    import android.hardware.camera2.CameraCaptureSession;
    import android.hardware.camera2.CameraCharacteristics;
    import android.hardware.camera2.CameraDevice;
    import android.hardware.camera2.CameraManager;
    import android.hardware.camera2.CameraMetadata;
    import android.hardware.camera2.CaptureRequest;
    import android.hardware.camera2.TotalCaptureResult;
    import android.hardware.camera2.params.StreamConfigurationMap;
    import android.media.Image;
    import android.media.ImageReader;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.HandlerThread;
    import android.support.annotation.NonNull;
    import android.support.v4.app.ActivityCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.util.Size;
    import android.util.SparseIntArray;
    import android.view.Surface;
    import android.view.TextureView;
    import android.view.View;
    import android.widget.Toast;



    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.nio.ByteBuffer;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    public class sleepingtime extends AppCompatActivity {
    private static final String TAG = "sleepingtime";
    private Handler mHandler = new Handler();
    private TextureView textureView;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
    ORIENTATIONS.append(Surface.ROTATION_0, 90);
    ORIENTATIONS.append(Surface.ROTATION_90, 0);
    ORIENTATIONS.append(Surface.ROTATION_180, 270);
    ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }
    private String cameraId;
    protected CameraDevice cameraDevice;
    protected CameraCaptureSession cameraCaptureSessions;
    protected CaptureRequest captureRequest;
    protected CaptureRequest.Builder captureRequestBuilder;
    private Size imageDimension;
    private ImageReader imageReader;
    private File file;
    private static final int REQUEST_CAMERA_PERMISSION = 200;
    private boolean mFlashSupported;
    private Handler mBackgroundHandler;
    private HandlerThread mBackgroundThread;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sleepingtime);
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); //hide navbar
    textureView = (TextureView) findViewById(R.id.textureView);
    assert textureView != null;
    textureView.setSurfaceTextureListener(textureListener);
    Log.i(TAG,"good Morning");

    takePicture();
    //goToMain(5000);
    }

    TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
    //open your camera here
    openCamera();
    }
    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
    // Transform you image captured size according to the surface width and height
    }
    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
    return false;
    }
    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    }
    };

    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
    @Override
    public void onOpened(CameraDevice camera) {
    //This is called when the camera is open
    Log.e(TAG, "onOpened");
    cameraDevice = camera;
    createCameraPreview();
    }
    @Override
    public void onDisconnected(CameraDevice camera) {
    cameraDevice.close();
    }
    @Override
    public void onError(CameraDevice camera, int error) {
    cameraDevice.close();
    cameraDevice = null;
    }
    };
    final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
    @Override
    public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
    super.onCaptureCompleted(session, request, result);
    Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
    createCameraPreview();
    }
    };
    protected void startBackgroundThread() {
    mBackgroundThread = new HandlerThread("Camera Background");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
    protected void stopBackgroundThread() {
    mBackgroundThread.quitSafely();
    try {
    mBackgroundThread.join();
    mBackgroundThread = null;
    mBackgroundHandler = null;
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    protected void takePicture() {
    if(null == cameraDevice) {
    Log.e(TAG, "cameraDevice is null");
    return;
    }
    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
    Log.i(TAG, "Kammera: " + manager.getCameraIdList());
    CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
    Size jpegSizes = null;
    if (characteristics != null) {
    jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
    }
    int width = 640;
    int height = 480;
    if (jpegSizes != null && 0 < jpegSizes.length) {
    width = jpegSizes[0].getWidth();
    height = jpegSizes[0].getHeight();
    }
    ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
    List<Surface> outputSurfaces = new ArrayList<Surface>(2);
    outputSurfaces.add(reader.getSurface());
    outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
    final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
    captureBuilder.addTarget(reader.getSurface());
    captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    // Orientation
    int rotation = getWindowManager().getDefaultDisplay().getRotation();
    captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
    final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
    ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
    @Override
    public void onImageAvailable(ImageReader reader) {
    Image image = null;
    try {
    image = reader.acquireLatestImage();
    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    byte bytes = new byte[buffer.capacity()];
    buffer.get(bytes);
    save(bytes);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (image != null) {
    image.close();
    }
    }
    }
    private void save(byte bytes) throws IOException {
    OutputStream output = null;
    try {
    output = new FileOutputStream(file);
    output.write(bytes);
    } finally {
    if (null != output) {
    output.close();
    }
    }
    }
    };
    reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
    final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
    @Override
    public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
    super.onCaptureCompleted(session, request, result);
    Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
    createCameraPreview();
    }
    };
    cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
    @Override
    public void onConfigured(CameraCaptureSession session) {
    try {
    session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
    } catch (CameraAccessException e) {
    e.printStackTrace();
    }
    }
    @Override
    public void onConfigureFailed(CameraCaptureSession session) {
    }
    }, mBackgroundHandler);
    } catch (CameraAccessException e) {
    e.printStackTrace();
    }
    }
    protected void createCameraPreview() {
    try {
    SurfaceTexture texture = textureView.getSurfaceTexture();
    assert texture != null;
    texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
    Surface surface = new Surface(texture);
    captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
    captureRequestBuilder.addTarget(surface);
    cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
    @Override
    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
    //The camera is already closed
    if (null == cameraDevice) {
    return;
    }
    // When the session is ready, we start displaying the preview.
    cameraCaptureSessions = cameraCaptureSession;
    updatePreview();
    }
    @Override
    public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
    Toast.makeText(sleepingtime.this, "Configuration change", Toast.LENGTH_SHORT).show();
    }
    }, null);
    } catch (CameraAccessException e) {
    e.printStackTrace();
    }
    }
    private void openCamera() {
    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    Log.e(TAG, "is camera open");
    try {
    cameraId = manager.getCameraIdList()[0];
    CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
    StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
    assert map != null;
    imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
    // Add permission for camera and let user grant the permission
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(sleepingtime.this, new String{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
    return;
    }
    manager.openCamera(cameraId, stateCallback, null);
    } catch (CameraAccessException e) {
    e.printStackTrace();
    }
    Log.e(TAG, "openCamera X");
    }
    protected void updatePreview() {
    if(null == cameraDevice) {
    Log.e(TAG, "updatePreview error, return");
    }
    captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    try {
    cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
    } catch (CameraAccessException e) {
    e.printStackTrace();
    }
    }
    private void closeCamera() {
    if (null != cameraDevice) {
    cameraDevice.close();
    cameraDevice = null;
    }
    if (null != imageReader) {
    imageReader.close();
    imageReader = null;
    }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions, @NonNull int grantResults) {
    if (requestCode == REQUEST_CAMERA_PERMISSION) {
    if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
    // close the app
    Toast.makeText(sleepingtime.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
    finish();
    }
    }
    }
    @Override
    protected void onResume() {
    super.onResume();
    Log.e(TAG, "onResume");
    startBackgroundThread();
    if (textureView.isAvailable()) {
    openCamera();
    } else {
    textureView.setSurfaceTextureListener(textureListener);
    }
    }
    @Override
    protected void onPause() {
    Log.e(TAG, "onPause");
    //closeCamera();
    stopBackgroundThread();
    super.onPause();
    }



    public void goToMain(int countdownms){
    //countdownms entspricht der Zeit bis zum Seitenwechsel in ms
    mHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
    try {
    Intent intent = new Intent(sleepingtime.this, MainActivity.class);
    startActivity(intent);
    } catch(Exception e){
    e.printStackTrace();
    Log.i(TAG, "Error calling activity MainActivity " + e);
    }
    }
    }, countdownms);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
    getWindow().getDecorView().setSystemUiVisibility(
    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
    | View.SYSTEM_UI_FLAG_FULLSCREEN
    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
    }

    }


    Thanks for your help!










    share|improve this question

























      0












      0








      0








      I'm trying to implement a camera into my android-app, for which I'm using the android.hardware.camera2 package. I did manage to somehow open the camera on my device, however it won't take a picture, because the first if-statement in takePicture():



          if(null == cameraDevice) {
      Log.e(TAG, "cameraDevice is null");
      return;
      }


      apperently gets null for cameraDevice, according to my logcat.
      I think, this happens because i did something wrong or Android Studio got something wrong with my dependencies.



      dependencies {
      implementation fileTree(include: ['*.jar'], dir: 'libs')
      implementation 'com.android.support:appcompat-v7:28.0.0'
      implementation 'com.android.support.constraint:constraint-layout:1.1.3'
      implementation 'com.android.support:design:28.0.0'
      implementation 'com.android.support:support-annotations:28.0.0'

      testImplementation 'junit:junit:4.12'
      androidTestImplementation 'com.android.support.test:runner:1.0.2'
      androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
      }


      While imports work fine for my own .java's, they "cannot resolve symbol.''"
      in the imported CameraDevice.java (picture of the failing imports)
      So, even though my project compiles with no errors, it doesn't work, because the imported CameraDevice can't import their imports properly.



      import android.annotation.NonNull;
      import android.annotation.Nullable;
      import android.annotation.IntDef;
      import android.annotation.SystemApi;
      import static android.hardware.camera2.ICameraDeviceUser.NORMAL_MODE;
      import static android.hardware.camera2.ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE;


      I tried:



      Clean & Rebuild



      Invalidate Chaches/Restart



      Deleting .gradle + .idea



      using different versions of com.android.support:support-annotations



      reinstalling AS



      so far, with no success.



      I had a similar problem with the JSON-package in the same project, which i couldn't resolve at all.



      this is my code:



      import android.Manifest;
      import android.content.Context;
      import android.content.Intent;
      import android.content.pm.PackageManager;
      import android.graphics.ImageFormat;
      import android.graphics.SurfaceTexture;
      import android.hardware.camera2.CameraAccessException;
      import android.hardware.camera2.CameraCaptureSession;
      import android.hardware.camera2.CameraCharacteristics;
      import android.hardware.camera2.CameraDevice;
      import android.hardware.camera2.CameraManager;
      import android.hardware.camera2.CameraMetadata;
      import android.hardware.camera2.CaptureRequest;
      import android.hardware.camera2.TotalCaptureResult;
      import android.hardware.camera2.params.StreamConfigurationMap;
      import android.media.Image;
      import android.media.ImageReader;
      import android.os.Bundle;
      import android.os.Environment;
      import android.os.Handler;
      import android.os.HandlerThread;
      import android.support.annotation.NonNull;
      import android.support.v4.app.ActivityCompat;
      import android.support.v7.app.AppCompatActivity;
      import android.util.Log;
      import android.util.Size;
      import android.util.SparseIntArray;
      import android.view.Surface;
      import android.view.TextureView;
      import android.view.View;
      import android.widget.Toast;



      import java.io.File;
      import java.io.FileNotFoundException;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.OutputStream;
      import java.nio.ByteBuffer;
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;

      public class sleepingtime extends AppCompatActivity {
      private static final String TAG = "sleepingtime";
      private Handler mHandler = new Handler();
      private TextureView textureView;
      private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
      static {
      ORIENTATIONS.append(Surface.ROTATION_0, 90);
      ORIENTATIONS.append(Surface.ROTATION_90, 0);
      ORIENTATIONS.append(Surface.ROTATION_180, 270);
      ORIENTATIONS.append(Surface.ROTATION_270, 180);
      }
      private String cameraId;
      protected CameraDevice cameraDevice;
      protected CameraCaptureSession cameraCaptureSessions;
      protected CaptureRequest captureRequest;
      protected CaptureRequest.Builder captureRequestBuilder;
      private Size imageDimension;
      private ImageReader imageReader;
      private File file;
      private static final int REQUEST_CAMERA_PERMISSION = 200;
      private boolean mFlashSupported;
      private Handler mBackgroundHandler;
      private HandlerThread mBackgroundThread;


      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_sleepingtime);
      getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); //hide navbar
      textureView = (TextureView) findViewById(R.id.textureView);
      assert textureView != null;
      textureView.setSurfaceTextureListener(textureListener);
      Log.i(TAG,"good Morning");

      takePicture();
      //goToMain(5000);
      }

      TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
      @Override
      public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
      //open your camera here
      openCamera();
      }
      @Override
      public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
      // Transform you image captured size according to the surface width and height
      }
      @Override
      public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
      return false;
      }
      @Override
      public void onSurfaceTextureUpdated(SurfaceTexture surface) {
      }
      };

      private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
      @Override
      public void onOpened(CameraDevice camera) {
      //This is called when the camera is open
      Log.e(TAG, "onOpened");
      cameraDevice = camera;
      createCameraPreview();
      }
      @Override
      public void onDisconnected(CameraDevice camera) {
      cameraDevice.close();
      }
      @Override
      public void onError(CameraDevice camera, int error) {
      cameraDevice.close();
      cameraDevice = null;
      }
      };
      final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
      @Override
      public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
      super.onCaptureCompleted(session, request, result);
      Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
      createCameraPreview();
      }
      };
      protected void startBackgroundThread() {
      mBackgroundThread = new HandlerThread("Camera Background");
      mBackgroundThread.start();
      mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
      }
      protected void stopBackgroundThread() {
      mBackgroundThread.quitSafely();
      try {
      mBackgroundThread.join();
      mBackgroundThread = null;
      mBackgroundHandler = null;
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      protected void takePicture() {
      if(null == cameraDevice) {
      Log.e(TAG, "cameraDevice is null");
      return;
      }
      CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
      try {
      Log.i(TAG, "Kammera: " + manager.getCameraIdList());
      CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
      Size jpegSizes = null;
      if (characteristics != null) {
      jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
      }
      int width = 640;
      int height = 480;
      if (jpegSizes != null && 0 < jpegSizes.length) {
      width = jpegSizes[0].getWidth();
      height = jpegSizes[0].getHeight();
      }
      ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
      List<Surface> outputSurfaces = new ArrayList<Surface>(2);
      outputSurfaces.add(reader.getSurface());
      outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
      final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
      captureBuilder.addTarget(reader.getSurface());
      captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
      // Orientation
      int rotation = getWindowManager().getDefaultDisplay().getRotation();
      captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
      final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
      ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
      @Override
      public void onImageAvailable(ImageReader reader) {
      Image image = null;
      try {
      image = reader.acquireLatestImage();
      ByteBuffer buffer = image.getPlanes()[0].getBuffer();
      byte bytes = new byte[buffer.capacity()];
      buffer.get(bytes);
      save(bytes);
      } catch (FileNotFoundException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      } finally {
      if (image != null) {
      image.close();
      }
      }
      }
      private void save(byte bytes) throws IOException {
      OutputStream output = null;
      try {
      output = new FileOutputStream(file);
      output.write(bytes);
      } finally {
      if (null != output) {
      output.close();
      }
      }
      }
      };
      reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
      final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
      @Override
      public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
      super.onCaptureCompleted(session, request, result);
      Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
      createCameraPreview();
      }
      };
      cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
      @Override
      public void onConfigured(CameraCaptureSession session) {
      try {
      session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      @Override
      public void onConfigureFailed(CameraCaptureSession session) {
      }
      }, mBackgroundHandler);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      protected void createCameraPreview() {
      try {
      SurfaceTexture texture = textureView.getSurfaceTexture();
      assert texture != null;
      texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
      Surface surface = new Surface(texture);
      captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
      captureRequestBuilder.addTarget(surface);
      cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
      @Override
      public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
      //The camera is already closed
      if (null == cameraDevice) {
      return;
      }
      // When the session is ready, we start displaying the preview.
      cameraCaptureSessions = cameraCaptureSession;
      updatePreview();
      }
      @Override
      public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
      Toast.makeText(sleepingtime.this, "Configuration change", Toast.LENGTH_SHORT).show();
      }
      }, null);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      private void openCamera() {
      CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
      Log.e(TAG, "is camera open");
      try {
      cameraId = manager.getCameraIdList()[0];
      CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
      StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
      assert map != null;
      imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
      // Add permission for camera and let user grant the permission
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(sleepingtime.this, new String{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
      return;
      }
      manager.openCamera(cameraId, stateCallback, null);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      Log.e(TAG, "openCamera X");
      }
      protected void updatePreview() {
      if(null == cameraDevice) {
      Log.e(TAG, "updatePreview error, return");
      }
      captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
      try {
      cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      private void closeCamera() {
      if (null != cameraDevice) {
      cameraDevice.close();
      cameraDevice = null;
      }
      if (null != imageReader) {
      imageReader.close();
      imageReader = null;
      }
      }
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String permissions, @NonNull int grantResults) {
      if (requestCode == REQUEST_CAMERA_PERMISSION) {
      if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
      // close the app
      Toast.makeText(sleepingtime.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
      finish();
      }
      }
      }
      @Override
      protected void onResume() {
      super.onResume();
      Log.e(TAG, "onResume");
      startBackgroundThread();
      if (textureView.isAvailable()) {
      openCamera();
      } else {
      textureView.setSurfaceTextureListener(textureListener);
      }
      }
      @Override
      protected void onPause() {
      Log.e(TAG, "onPause");
      //closeCamera();
      stopBackgroundThread();
      super.onPause();
      }



      public void goToMain(int countdownms){
      //countdownms entspricht der Zeit bis zum Seitenwechsel in ms
      mHandler.postDelayed(new Runnable() {
      @Override
      public void run() {
      try {
      Intent intent = new Intent(sleepingtime.this, MainActivity.class);
      startActivity(intent);
      } catch(Exception e){
      e.printStackTrace();
      Log.i(TAG, "Error calling activity MainActivity " + e);
      }
      }
      }, countdownms);

      }

      @Override
      public void onWindowFocusChanged(boolean hasFocus) {
      super.onWindowFocusChanged(hasFocus);
      if (hasFocus) {
      getWindow().getDecorView().setSystemUiVisibility(
      View.SYSTEM_UI_FLAG_LAYOUT_STABLE
      | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
      | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
      | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
      | View.SYSTEM_UI_FLAG_FULLSCREEN
      | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
      }
      }

      }


      Thanks for your help!










      share|improve this question














      I'm trying to implement a camera into my android-app, for which I'm using the android.hardware.camera2 package. I did manage to somehow open the camera on my device, however it won't take a picture, because the first if-statement in takePicture():



          if(null == cameraDevice) {
      Log.e(TAG, "cameraDevice is null");
      return;
      }


      apperently gets null for cameraDevice, according to my logcat.
      I think, this happens because i did something wrong or Android Studio got something wrong with my dependencies.



      dependencies {
      implementation fileTree(include: ['*.jar'], dir: 'libs')
      implementation 'com.android.support:appcompat-v7:28.0.0'
      implementation 'com.android.support.constraint:constraint-layout:1.1.3'
      implementation 'com.android.support:design:28.0.0'
      implementation 'com.android.support:support-annotations:28.0.0'

      testImplementation 'junit:junit:4.12'
      androidTestImplementation 'com.android.support.test:runner:1.0.2'
      androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
      }


      While imports work fine for my own .java's, they "cannot resolve symbol.''"
      in the imported CameraDevice.java (picture of the failing imports)
      So, even though my project compiles with no errors, it doesn't work, because the imported CameraDevice can't import their imports properly.



      import android.annotation.NonNull;
      import android.annotation.Nullable;
      import android.annotation.IntDef;
      import android.annotation.SystemApi;
      import static android.hardware.camera2.ICameraDeviceUser.NORMAL_MODE;
      import static android.hardware.camera2.ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE;


      I tried:



      Clean & Rebuild



      Invalidate Chaches/Restart



      Deleting .gradle + .idea



      using different versions of com.android.support:support-annotations



      reinstalling AS



      so far, with no success.



      I had a similar problem with the JSON-package in the same project, which i couldn't resolve at all.



      this is my code:



      import android.Manifest;
      import android.content.Context;
      import android.content.Intent;
      import android.content.pm.PackageManager;
      import android.graphics.ImageFormat;
      import android.graphics.SurfaceTexture;
      import android.hardware.camera2.CameraAccessException;
      import android.hardware.camera2.CameraCaptureSession;
      import android.hardware.camera2.CameraCharacteristics;
      import android.hardware.camera2.CameraDevice;
      import android.hardware.camera2.CameraManager;
      import android.hardware.camera2.CameraMetadata;
      import android.hardware.camera2.CaptureRequest;
      import android.hardware.camera2.TotalCaptureResult;
      import android.hardware.camera2.params.StreamConfigurationMap;
      import android.media.Image;
      import android.media.ImageReader;
      import android.os.Bundle;
      import android.os.Environment;
      import android.os.Handler;
      import android.os.HandlerThread;
      import android.support.annotation.NonNull;
      import android.support.v4.app.ActivityCompat;
      import android.support.v7.app.AppCompatActivity;
      import android.util.Log;
      import android.util.Size;
      import android.util.SparseIntArray;
      import android.view.Surface;
      import android.view.TextureView;
      import android.view.View;
      import android.widget.Toast;



      import java.io.File;
      import java.io.FileNotFoundException;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.OutputStream;
      import java.nio.ByteBuffer;
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;

      public class sleepingtime extends AppCompatActivity {
      private static final String TAG = "sleepingtime";
      private Handler mHandler = new Handler();
      private TextureView textureView;
      private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
      static {
      ORIENTATIONS.append(Surface.ROTATION_0, 90);
      ORIENTATIONS.append(Surface.ROTATION_90, 0);
      ORIENTATIONS.append(Surface.ROTATION_180, 270);
      ORIENTATIONS.append(Surface.ROTATION_270, 180);
      }
      private String cameraId;
      protected CameraDevice cameraDevice;
      protected CameraCaptureSession cameraCaptureSessions;
      protected CaptureRequest captureRequest;
      protected CaptureRequest.Builder captureRequestBuilder;
      private Size imageDimension;
      private ImageReader imageReader;
      private File file;
      private static final int REQUEST_CAMERA_PERMISSION = 200;
      private boolean mFlashSupported;
      private Handler mBackgroundHandler;
      private HandlerThread mBackgroundThread;


      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_sleepingtime);
      getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); //hide navbar
      textureView = (TextureView) findViewById(R.id.textureView);
      assert textureView != null;
      textureView.setSurfaceTextureListener(textureListener);
      Log.i(TAG,"good Morning");

      takePicture();
      //goToMain(5000);
      }

      TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
      @Override
      public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
      //open your camera here
      openCamera();
      }
      @Override
      public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
      // Transform you image captured size according to the surface width and height
      }
      @Override
      public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
      return false;
      }
      @Override
      public void onSurfaceTextureUpdated(SurfaceTexture surface) {
      }
      };

      private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
      @Override
      public void onOpened(CameraDevice camera) {
      //This is called when the camera is open
      Log.e(TAG, "onOpened");
      cameraDevice = camera;
      createCameraPreview();
      }
      @Override
      public void onDisconnected(CameraDevice camera) {
      cameraDevice.close();
      }
      @Override
      public void onError(CameraDevice camera, int error) {
      cameraDevice.close();
      cameraDevice = null;
      }
      };
      final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
      @Override
      public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
      super.onCaptureCompleted(session, request, result);
      Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
      createCameraPreview();
      }
      };
      protected void startBackgroundThread() {
      mBackgroundThread = new HandlerThread("Camera Background");
      mBackgroundThread.start();
      mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
      }
      protected void stopBackgroundThread() {
      mBackgroundThread.quitSafely();
      try {
      mBackgroundThread.join();
      mBackgroundThread = null;
      mBackgroundHandler = null;
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      protected void takePicture() {
      if(null == cameraDevice) {
      Log.e(TAG, "cameraDevice is null");
      return;
      }
      CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
      try {
      Log.i(TAG, "Kammera: " + manager.getCameraIdList());
      CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
      Size jpegSizes = null;
      if (characteristics != null) {
      jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
      }
      int width = 640;
      int height = 480;
      if (jpegSizes != null && 0 < jpegSizes.length) {
      width = jpegSizes[0].getWidth();
      height = jpegSizes[0].getHeight();
      }
      ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
      List<Surface> outputSurfaces = new ArrayList<Surface>(2);
      outputSurfaces.add(reader.getSurface());
      outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
      final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
      captureBuilder.addTarget(reader.getSurface());
      captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
      // Orientation
      int rotation = getWindowManager().getDefaultDisplay().getRotation();
      captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
      final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
      ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
      @Override
      public void onImageAvailable(ImageReader reader) {
      Image image = null;
      try {
      image = reader.acquireLatestImage();
      ByteBuffer buffer = image.getPlanes()[0].getBuffer();
      byte bytes = new byte[buffer.capacity()];
      buffer.get(bytes);
      save(bytes);
      } catch (FileNotFoundException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      } finally {
      if (image != null) {
      image.close();
      }
      }
      }
      private void save(byte bytes) throws IOException {
      OutputStream output = null;
      try {
      output = new FileOutputStream(file);
      output.write(bytes);
      } finally {
      if (null != output) {
      output.close();
      }
      }
      }
      };
      reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
      final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
      @Override
      public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
      super.onCaptureCompleted(session, request, result);
      Toast.makeText(sleepingtime.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
      createCameraPreview();
      }
      };
      cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
      @Override
      public void onConfigured(CameraCaptureSession session) {
      try {
      session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      @Override
      public void onConfigureFailed(CameraCaptureSession session) {
      }
      }, mBackgroundHandler);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      protected void createCameraPreview() {
      try {
      SurfaceTexture texture = textureView.getSurfaceTexture();
      assert texture != null;
      texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
      Surface surface = new Surface(texture);
      captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
      captureRequestBuilder.addTarget(surface);
      cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
      @Override
      public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
      //The camera is already closed
      if (null == cameraDevice) {
      return;
      }
      // When the session is ready, we start displaying the preview.
      cameraCaptureSessions = cameraCaptureSession;
      updatePreview();
      }
      @Override
      public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
      Toast.makeText(sleepingtime.this, "Configuration change", Toast.LENGTH_SHORT).show();
      }
      }, null);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      private void openCamera() {
      CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
      Log.e(TAG, "is camera open");
      try {
      cameraId = manager.getCameraIdList()[0];
      CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
      StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
      assert map != null;
      imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
      // Add permission for camera and let user grant the permission
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(sleepingtime.this, new String{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
      return;
      }
      manager.openCamera(cameraId, stateCallback, null);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      Log.e(TAG, "openCamera X");
      }
      protected void updatePreview() {
      if(null == cameraDevice) {
      Log.e(TAG, "updatePreview error, return");
      }
      captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
      try {
      cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
      } catch (CameraAccessException e) {
      e.printStackTrace();
      }
      }
      private void closeCamera() {
      if (null != cameraDevice) {
      cameraDevice.close();
      cameraDevice = null;
      }
      if (null != imageReader) {
      imageReader.close();
      imageReader = null;
      }
      }
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String permissions, @NonNull int grantResults) {
      if (requestCode == REQUEST_CAMERA_PERMISSION) {
      if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
      // close the app
      Toast.makeText(sleepingtime.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
      finish();
      }
      }
      }
      @Override
      protected void onResume() {
      super.onResume();
      Log.e(TAG, "onResume");
      startBackgroundThread();
      if (textureView.isAvailable()) {
      openCamera();
      } else {
      textureView.setSurfaceTextureListener(textureListener);
      }
      }
      @Override
      protected void onPause() {
      Log.e(TAG, "onPause");
      //closeCamera();
      stopBackgroundThread();
      super.onPause();
      }



      public void goToMain(int countdownms){
      //countdownms entspricht der Zeit bis zum Seitenwechsel in ms
      mHandler.postDelayed(new Runnable() {
      @Override
      public void run() {
      try {
      Intent intent = new Intent(sleepingtime.this, MainActivity.class);
      startActivity(intent);
      } catch(Exception e){
      e.printStackTrace();
      Log.i(TAG, "Error calling activity MainActivity " + e);
      }
      }
      }, countdownms);

      }

      @Override
      public void onWindowFocusChanged(boolean hasFocus) {
      super.onWindowFocusChanged(hasFocus);
      if (hasFocus) {
      getWindow().getDecorView().setSystemUiVisibility(
      View.SYSTEM_UI_FLAG_LAYOUT_STABLE
      | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
      | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
      | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
      | View.SYSTEM_UI_FLAG_FULLSCREEN
      | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
      }
      }

      }


      Thanks for your help!







      java android android-studio android-gradle dependencies






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 19:16









      Nils KrautkremerNils Krautkremer

      207




      207
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461560%2fcannot-resolve-imports-of-cameradevice-java-from-android-hardware-camera2-packag%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461560%2fcannot-resolve-imports-of-cameradevice-java-from-android-hardware-camera2-packag%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

          Calculate evaluation metrics using cross_val_predict sklearn

          Insert data from modal to MySQL (multiple modal on website)