List of usage examples for android.content Context CAMERA_SERVICE
String CAMERA_SERVICE
To view the source code for android.content Context CAMERA_SERVICE.
Click Source Link
From source file:com.example.android.mediarecorder.MainActivity.java
private boolean preparePreview() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { try {/*w w w.ja v a 2 s . c om*/ CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); String id = manager.getCameraIdList()[0]; CameraCharacteristics characteristics = manager.getCameraCharacteristics(id); sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); } catch (CameraAccessException e) { Log.e("ERROR", "Cannot access Camera2 API"); e.printStackTrace(); } } Log.i(TAG, "Preparing Camera Preview"); // BEGIN_INCLUDE (configure_preview) // mCamera = CameraHelper.getDefaultCameraInstance(); // We need to make sure that our preview and recording video size are supported by the // camera. Query camera to find all the sizes and choose the optimal size given the // dimensions of our preview surface. Camera.Parameters parameters = mCamera.getParameters(); List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes(); List<Camera.Size> mSupportedVideoSizes = parameters.getSupportedVideoSizes(); Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes, mSupportedPreviewSizes, mPreview.getWidth(), mPreview.getHeight()); // Use the same size for recording profile. CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); profile.videoFrameWidth = optimalSize.width; profile.videoFrameHeight = optimalSize.height; // likewise for the camera object itself. parameters.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight); mCamera.setParameters(parameters); try { // Requires API level 11+, For backward compatibility use {@link setPreviewDisplay} // with {@link SurfaceView} // mCamera.setPreviewTexture(mPreview.getSurfaceTexture()); mHolder = mPreview.getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // mHolder.setKeepScreenOn(true); setCameraDisplayOrientation(0); mCamera.setPreviewDisplay(mPreview.getHolder()); mCamera.startPreview(); Log.i(TAG, "Setting Preview Display"); } catch (IOException e) { Log.e(TAG, "Surface texture is unavailable or unsuitable" + e.getMessage()); return false; } // END_INCLUDE (configure_preview) return true; }
From source file:com.google.android.apps.watchme.StreamerActivity.java
private void connectCamera() { CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try {//w ww . j a v a 2s. c om cameraManager.openCamera(cameraId, cameraDeviceCallback, backgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
From source file:com.android.camera2.its.ItsService.java
@Override public void onCreate() { try {//from w w w . j a v a 2s .co m mThreadExitFlag = false; // Get handle to camera manager. mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE); if (mCameraManager == null) { throw new ItsException("Failed to connect to camera manager"); } mBlockingCameraManager = new BlockingCameraManager(mCameraManager); mCameraListener = new BlockingStateCallback(); // Register for motion events. mEvents = new LinkedList<MySensorEvent>(); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mSensorManager.registerListener(this, mAccelSensor, SensorManager.SENSOR_DELAY_FASTEST); mSensorManager.registerListener(this, mMagSensor, SensorManager.SENSOR_DELAY_FASTEST); mSensorManager.registerListener(this, mGyroSensor, SensorManager.SENSOR_DELAY_FASTEST); // Get a handle to the system vibrator. mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Create threads to receive images and save them. for (int i = 0; i < MAX_NUM_OUTPUT_SURFACES; i++) { mSaveThreads[i] = new HandlerThread("SaveThread" + i); mSaveThreads[i].start(); mSaveHandlers[i] = new Handler(mSaveThreads[i].getLooper()); } // Create a thread to handle object serialization. (new Thread(new SerializerRunnable())).start(); ; // Create a thread to receive capture results and process them. mResultThread = new HandlerThread("ResultThread"); mResultThread.start(); mResultHandler = new Handler(mResultThread.getLooper()); // Create a thread for the camera device. mCameraThread = new HandlerThread("ItsCameraThread"); mCameraThread.start(); mCameraHandler = new Handler(mCameraThread.getLooper()); // Create a thread to process commands, listening on a TCP socket. mSocketRunnableObj = new SocketRunnable(); (new Thread(mSocketRunnableObj)).start(); } catch (ItsException e) { Logt.e(TAG, "Service failed to start: ", e); } }
From source file:com.raulh82vlc.face_detection_sample.camera2.presentation.FDCamera2Presenter.java
private void openCamera(int width, int height) { if (isViewAvailable()) { if (ActivityCompat.checkSelfPermission(activityView, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activityView, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activityView, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, FDCamera2Activity.PERMISSIONS_REQUEST_CAMERA); return; }// w w w. j av a 2 s . co m setUpCameraOutputs(width, height); configureTransform(previewSize.getHeight(), previewSize.getWidth()); // Add permission for camera and let user grant the permission CameraManager manager = (CameraManager) activityView.getSystemService(Context.CAMERA_SERVICE); try { if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } String[] cameras = manager.getCameraIdList(); String cameraId = cameras[1]; // CameraCharacteristics characteristics // = manager.getCameraCharacteristics(cameraId); // Check detectModes // int[] faceDetectModes = characteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES); manager.openCamera(cameraId, stateCallback, mainThread.get()); } catch (CameraAccessException e) { e.printStackTrace(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening.", e); } } }
From source file:com.example.camera2apidemo.Camera2Fragment.java
private String setUpCameraOutputs(int width, int height) { Activity activity = getActivity();/* w w w. j a va 2 s .com*/ CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : manager.getCameraIdList()) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // ??? We don't use a front facing camera in this sample. Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } // ?? ?? StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } // For still image captures, we use the largest available size. Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/2); mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler); // Check if the flash is supported. Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); mFlashSupported = available == null ? false : available; return cameraId; } } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. // ErrorDialog.newInstance(getString(R.string.camera_error)) // .show(getChildFragmentManager(), FRAGMENT_DIALOG); } return null; }
From source file:com.raulh82vlc.face_detection_sample.camera2.presentation.FDCamera2Presenter.java
/** * Sets up member variables related to camera. * * @param width The width of available size for camera preview * @param height The height of available size for camera preview *//*from www . j a va2 s . c om*/ private void setUpCameraOutputs(int width, int height) { if (isViewAvailable()) { CameraManager manager = (CameraManager) activityView.getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : manager.getCameraIdList()) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } imageDimension = map.getOutputSizes(SurfaceTexture.class)[0]; // For still image captures, we use the largest available size. Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea()); Point displaySize = new Point(); activityView.getWindowManager().getDefaultDisplay().getSize(displaySize); int rotatedPreviewWidth = width; int rotatedPreviewHeight = height; int maxPreviewWidth = displaySize.x; int maxPreviewHeight = displaySize.y; if (maxPreviewWidth > MAX_PREVIEW_WIDTH) { maxPreviewWidth = MAX_PREVIEW_WIDTH; } if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) { maxPreviewHeight = MAX_PREVIEW_HEIGHT; } // Danger, W.R.! Attempting to use too large a preview size could exceed the camera // bus' bandwidth limitation, resulting in gorgeous previews but the storage of // garbage capture data. previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest); // We fit the aspect ratio of TextureView to the size of preview we picked. int orientation = activityView.getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { activityView.getTextureView().setAspectRatio(previewSize.getWidth(), previewSize.getHeight()); } else { activityView.getTextureView().setAspectRatio(previewSize.getHeight(), previewSize.getWidth()); } return; } } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. } } }
From source file:wisc.drivesense.vediorecorder.CameraFragment.java
/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. *//*from w w w . jav a 2s . c om*/ private void openCamera(int width, int height) { final Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { return; } CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { Log.d(TAG, "tryAcquire"); if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } Log.d(TAG, "check how many cameras"); for (int i = 0; i < manager.getCameraIdList().length; ++i) { Log.d(TAG, manager.getCameraIdList()[i]); } String cameraId = manager.getCameraIdList()[0]; // Choose the sizes for camera preview and video recording CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize); int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth()); } configureTransform(width, height); mMediaRecorder = new MediaRecorder(); manager.openCamera(cameraId, mStateCallback, null); } catch (CameraAccessException e) { Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show(); activity.finish(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. //ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(), FRAGMENT_DIALOG); Log.e(TAG, "This camera does not suppport Camera2API"); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening."); } }
From source file:com.tzutalin.dlibtest.CameraConnectionFragment.java
/** * Sets up member variables related to camera. * * @param width The width of available size for camera preview * @param height The height of available size for camera preview */// w w w. j ava2s. c o m @DebugLog @SuppressLint("LongLogTag") private void setUpCameraOutputs(final int width, final int height) { final Activity activity = getActivity(); final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { SparseArray<Integer> cameraFaceTypeMap = new SparseArray<>(); // Check the facing types of camera devices for (final String cameraId : manager.getCameraIdList()) { final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { if (cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_FRONT) != null) { cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_FRONT, cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_FRONT) + 1); } else { cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_FRONT, 1); } } if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) { if (cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_FRONT) != null) { cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_BACK, cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_BACK) + 1); } else { cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_BACK, 1); } } } Integer num_facing_back_camera = cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_BACK); for (final String cameraId : manager.getCameraIdList()) { final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); // If facing back camera or facing external camera exist, we won't use facing front camera if (num_facing_back_camera != null && num_facing_back_camera > 0) { // We don't use a front facing camera in this sample if there are other camera device facing types if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } } final StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } // For still image captures, we use the largest available size. final Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.YUV_420_888)), new CompareSizesByArea()); // Danger, W.R.! Attempting to use too large a preview size could exceed the camera // bus' bandwidth limitation, resulting in gorgeous previews but the storage of // garbage capture data. previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, largest); // We fit the aspect ratio of TextureView to the size of preview we picked. final int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight()); } else { textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth()); } CameraConnectionFragment.this.cameraId = cameraId; return; } } catch (final CameraAccessException e) { Timber.tag(TAG).e("Exception!", e); } catch (final NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(), FRAGMENT_DIALOG); } }
From source file:com.microsoft.projectoxford.emotionsample.RecognizeActivity.java
protected void takePicture() { if (null == cameraDevice) { Log.e("LOG", "cameraDevice is null"); return;//from ww w .j av a 2 s . co m } CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); mBitmap = textureView.getBitmap(); if (mBitmap != null) { doRecognize(); } /* try { 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"); //---------// mImageUri = Uri.fromFile(file); mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri( mImageUri, getContentResolver()); mBitmap = textureView.getBitmap(); if (mBitmap != null) { doRecognize(); } //-----------// 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(RecognizeActivity.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(); }*/ }
From source file:com.example.camera2apidemo.Camera2Fragment.java
/** * Opens the camera specified by {@link Camera2Fragment#mCameraId}. *///from w w w . ja v a 2s . co m private void openCamera(int width, int height) { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { FragmentCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA }, 1); return; } mCameraId = setUpCameraOutputs(width, height); // ?CameraId???CameraIdCamera?CameraDevice Activity activity = getActivity(); CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { if (!mSemaphore.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } // ??CameraId // ?CameraDeviceStateCallback??CameraDevice // ?Handler?null? manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening.", e); } }