Java 类android.hardware.camera2.CameraManager 实例源码

项目:CameraSample    文件:CameraV2Activity.java   
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera_v2);

    CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
    try {
        for (String cameraId : cameraManager.getCameraIdList()) {
            CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing.equals(CameraCharacteristics.LENS_FACING_FRONT)) {

            }
            // Do something with the characteristics
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
项目:ROLF-EV3    文件:PCVideoStreamer.java   
public void readyCamera() {
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        String pickedCamera = getCamera(manager);
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        manager.openCamera(pickedCamera, cameraStateCallback, null);
        imageReader = ImageReader.newInstance(videoWidth, videoHeight, 0x00000001 /*ImageFormat.YUV_420_888*/, 2 /* images buffered */);
        imageReader.setOnImageAvailableListener(onImageAvailableListener, null);
        Log.i(TAG, "imageReader created");
    } catch (CameraAccessException e){
        Log.e(TAG, e.getMessage());
    }
}
项目:TK_1701    文件:Camera2.java   
public void open() {
    try {
        CameraManager manager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) {
                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                mCameraSize = map.getOutputSizes(SurfaceTexture.class)[0];

                HandlerThread thread = new HandlerThread("OpenCamera");
                thread.start();
                Handler backgroundHandler = new Handler(thread.getLooper());

                manager.openCamera(cameraId, mCameraDeviceCallback, null);

                // カメラの物理的な情報を得る
                mCameraCharacteristics = manager.getCameraCharacteristics( cameraId );
                return;
            }
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
项目:Bixlight    文件:BixlightService.java   
private boolean setupCameraIfNeeded() {
    if (cameraId != null) {
        return true;
    }
    try {
        cameraId = cameraManager.getCameraIdList()[0];  // Usually back camera is at 0 position
    } catch (CameraAccessException e) {
        Log.v(TAG, "failed to set up camera");
        return false;
    }
    torchEnabled = false;
    Handler handler = new Handler();
    torchCallback = new CameraManager.TorchCallback() {
        @Override
        public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
            super.onTorchModeChanged(cameraId, enabled);
            torchEnabled = enabled;
        }
    };
    cameraManager.registerTorchCallback(torchCallback, handler);
    Log.v(TAG, "registered torch callback");
    return true;
}
项目:hella-renderscript    文件:CameraOps.java   
/**
 * Create a new camera ops thread.
 *
 * @param errorDisplayer listener for displaying error messages
 * @param readyListener  listener for notifying when camera is ready for requests
 * @param readyHandler   the handler for calling readyListener methods on
 */
CameraOps(CameraManager manager, ErrorDisplayer errorDisplayer,
        CameraReadyListener readyListener, Handler readyHandler) {
    mCameraThread = new HandlerThread("CameraOpsThread");
    mCameraThread.start();
    mCameraHandler = new Handler(mCameraThread.getLooper());

    if (manager == null || errorDisplayer == null || readyListener == null ||
            readyHandler == null) {
        throw new IllegalArgumentException("Need valid displayer, listener, handler");
    }

    mCameraManager = manager;
    mErrorDisplayer = errorDisplayer;
    mReadyListener = readyListener;
    mReadyHandler = readyHandler;
}
项目:habpanelviewer    文件:MotionDetectorCamera2.java   
@Override
protected String getCameraInfo() {
    String camStr = mContext.getString(R.string.camApi2) + "\n";
    CameraManager camManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
    try {
        for (String camId : camManager.getCameraIdList()) {
            camStr += mContext.getString(R.string.cameraId, camId) + ": ";

            CameraCharacteristics characteristics = camManager.getCameraCharacteristics(camId);
            Boolean hasFlash = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);

            camStr += (hasFlash ? mContext.getString(R.string.has) : mContext.getString(R.string.no))
                    + " " + mContext.getString(R.string.flash) + ", ";
            camStr += (facing == CameraCharacteristics.LENS_FACING_BACK ?
                    mContext.getString(R.string.backFacing) : mContext.getString(R.string.frontFacing)) + "\n";
        }
    } catch (CameraAccessException e) {
        camStr = mActivity.getString(R.string.failedAccessCamera) + ":" + e.getMessage();
    }

    return camStr.trim();
}
项目:habpanelviewer    文件:FlashController.java   
public FlashController(Context ctx, CameraManager cameraManager, ServerConnection serverConnection) throws CameraAccessException, IllegalAccessException {
    mCtx = ctx;
    camManager = cameraManager;
    mServerConnection = serverConnection;

    EventBus.getDefault().register(this);

    for (String camId : camManager.getCameraIdList()) {
        CameraCharacteristics characteristics = camManager.getCameraCharacteristics(camId);
        Boolean hasFlash = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
        Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);

        if (facing == CameraCharacteristics.LENS_FACING_BACK && hasFlash) {
            torchId = camId;
            break;
        }
    }

    if (torchId == null) {
        throw new IllegalAccessException(ctx.getString(R.string.couldNotFindBackFlash));
    }
}
项目:SCCameraView    文件:Camera2View.java   
@Override
public void collectRatioSizes() {
    ratioSizeList.clear();
    CameraCharacteristics characteristics;
    StreamConfigurationMap map = null;
    try {
        characteristics = ((CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE)).getCameraCharacteristics(Integer.toString(Integer.parseInt(getCameraId())));
        map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

    Size[] outputSizes = map.getOutputSizes(SurfaceTexture.class);
    if (outputSizes != null) {
        List<Double> ratioList = new ArrayList<>();
        for (Size size : outputSizes) {
            double ratio = (double) size.getWidth() / (double) size.getHeight();
            if (!ratioList.contains(ratio)) {
                ratioList.add(ratio);
                ratioSizeList.add(new AspectRatio(ratio, size.getWidth(), size.getHeight()));
            }
        }
    }
}
项目:AppRTC-Android    文件:Camera2Session.java   
private Camera2Session(CreateSessionCallback callback, Events events, Context applicationContext,
    CameraManager cameraManager, SurfaceTextureHelper surfaceTextureHelper,
    MediaRecorder mediaRecorder, String cameraId, int width, int height, int framerate) {
  Logging.d(TAG, "Create new camera2 session on camera " + cameraId);
  videoFrameEmitTrialEnabled =
      PeerConnectionFactory.fieldTrialsFindFullName(PeerConnectionFactory.VIDEO_FRAME_EMIT_TRIAL)
          .equals(PeerConnectionFactory.TRIAL_ENABLED);

  constructionTimeNs = System.nanoTime();

  this.cameraThreadHandler = new Handler();
  this.callback = callback;
  this.events = events;
  this.applicationContext = applicationContext;
  this.cameraManager = cameraManager;
  this.surfaceTextureHelper = surfaceTextureHelper;
  this.mediaRecorderSurface = (mediaRecorder != null) ? mediaRecorder.getSurface() : null;
  this.cameraId = cameraId;
  this.width = width;
  this.height = height;
  this.framerate = framerate;

  start();
}
项目:AppRTC-Android    文件:Camera2Enumerator.java   
/**
 * Checks if API is supported and all cameras have better than legacy support.
 */
public static boolean isSupported(Context context) {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    return false;
  }

  CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
  try {
    String[] cameraIds = cameraManager.getCameraIdList();
    for (String id : cameraIds) {
      CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
      if (characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
          == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
        return false;
      }
    }
    // On Android OS pre 4.4.2, a class will not load because of VerifyError if it contains a
    // catch statement with an Exception from a newer API, even if the code is never executed.
    // https://code.google.com/p/android/issues/detail?id=209129
  } catch (/* CameraAccessException */ AndroidException e) {
    Logging.e(TAG, "Camera access exception: " + e);
    return false;
  }
  return true;
}
项目:mao-android    文件:Camera2Fragment.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    log.i("onCreateView");
    View rootView = inflater.inflate(R.layout.fragment_camera, container, false);

    mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);

    mHandlerThread = new HandlerThread("CameraFragment_HandlerThread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());

    ttv_camera = (AutoFitTextureView) rootView.findViewById(R.id.ttv_camera);
    ttv_camera.setSurfaceTextureListener(this);

    tbtn_camera = (ToggleButton) rootView.findViewById(R.id.tbtn_camera);
    tbtn_camera.setOnCheckedChangeListener(this);

    return rootView;
}
项目:AndroidRTC    文件:Camera2Session.java   
private Camera2Session(CreateSessionCallback callback, Events events, Context applicationContext,
    CameraManager cameraManager, SurfaceTextureHelper surfaceTextureHelper, String cameraId,
    int width, int height, int framerate) {
  Logging.d(TAG, "Create new camera2 session on camera " + cameraId);

  constructionTimeNs = System.nanoTime();

  this.cameraThreadHandler = new Handler();
  this.callback = callback;
  this.events = events;
  this.applicationContext = applicationContext;
  this.cameraManager = cameraManager;
  this.surfaceTextureHelper = surfaceTextureHelper;
  this.cameraId = cameraId;
  this.width = width;
  this.height = height;
  this.framerate = framerate;

  start();
}
项目:AndroidRTC    文件:Camera2Enumerator.java   
/**
 * Checks if API is supported and all cameras have better than legacy support.
 */
public static boolean isSupported(Context context) {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    return false;
  }

  CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
  try {
    String[] cameraIds = cameraManager.getCameraIdList();
    for (String id : cameraIds) {
      CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
      if (characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
          == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
        return false;
      }
    }
    // On Android OS pre 4.4.2, a class will not load because of VerifyError if it contains a
    // catch statement with an Exception from a newer API, even if the code is never executed.
    // https://code.google.com/p/android/issues/detail?id=209129
  } catch (/* CameraAccessException */ AndroidException e) {
    Logging.e(TAG, "Camera access exception: " + e);
    return false;
  }
  return true;
}
项目:AndroidRTC    文件:Camera2CapturerTest.java   
SimpleCamera2(Context context, String deviceName) {
  cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
  looperThread = new LooperThread();
  looperThread.start();
  looperThread.waitToStart();
  cameraDeviceLock = new Object();
  openDoneSignal = new CountDownLatch(1);
  cameraDevice = null;
  Logging.d(TAG, "Opening simple camera2.");
  try {
    cameraManager.openCamera(deviceName, new CameraStateCallback(), looperThread.getHandler());
  } catch (CameraAccessException e) {
    fail("Simple camera2 CameraAccessException: " + e.getMessage());
  }

  Logging.d(TAG, "Waiting for simple camera2 to open.");
  ThreadUtils.awaitUninterruptibly(openDoneSignal);
  synchronized (cameraDeviceLock) {
    if (!openSucceeded) {
      fail("Opening simple camera2 failed.");
    }
  }
}
项目:BaseCore    文件:FlashlightController.java   
public FlashlightController(Context mContext) {
    mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);

    String cameraId = null;
    try {
        cameraId = getCameraId();
    } catch (Throwable e) {
        Log.e(TAG, "Couldn't initialize.", e);
        return;
    } finally {
        mCameraId = cameraId;
    }

    if (mCameraId != null) {
        ensureHandler();
        mCameraManager.registerTorchCallback(mTorchCallback, mHandler);
    }
}
项目:VideoCRE    文件:Camera2Session.java   
private Camera2Session(CreateSessionCallback callback, Events events, Context applicationContext,
    CameraManager cameraManager, SurfaceTextureHelper surfaceTextureHelper,
    MediaRecorder mediaRecorder, String cameraId, int width, int height, int framerate) {
  Logging.d(TAG, "Create new camera2 session on camera " + cameraId);

  constructionTimeNs = System.nanoTime();

  this.cameraThreadHandler = new Handler();
  this.callback = callback;
  this.events = events;
  this.applicationContext = applicationContext;
  this.cameraManager = cameraManager;
  this.surfaceTextureHelper = surfaceTextureHelper;
  this.mediaRecorderSurface = (mediaRecorder != null) ? mediaRecorder.getSurface() : null;
  this.cameraId = cameraId;
  this.width = width;
  this.height = height;
  this.framerate = framerate;
  this.activityOrientation = getDeviceOrientation();

  start();
}
项目:VideoCRE    文件:Camera2Enumerator.java   
/**
 * Checks if API is supported and all cameras have better than legacy support.
 */
public static boolean isSupported(Context context) {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    return false;
  }

  CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
  try {
    String[] cameraIds = cameraManager.getCameraIdList();
    for (String id : cameraIds) {
      CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
      if (characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
          == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
        return false;
      }
    }
    // On Android OS pre 4.4.2, a class will not load because of VerifyError if it contains a
    // catch statement with an Exception from a newer API, even if the code is never executed.
    // https://code.google.com/p/android/issues/detail?id=209129
  } catch (/* CameraAccessException */ AndroidException e) {
    Logging.e(TAG, "Camera access exception: " + e);
    return false;
  }
  return true;
}
项目:RLibrary    文件:FlashlightController.java   
public FlashlightController(Context mContext) {
    mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);

    String cameraId = null;
    try {
        cameraId = getCameraId();
    } catch (Throwable e) {
        Log.e(TAG, "Couldn't initialize.", e);
        return;
    } finally {
        mCameraId = cameraId;
    }

    if (mCameraId != null) {
        ensureHandler();
        mCameraManager.registerTorchCallback(mTorchCallback, mHandler);
    }
}
项目:TUI-ConsoleLauncher    文件:Flashlight2.java   
@Override
protected void turnOff() {
    if (this.getStatus()) {
        if (this.mCameraIDList != null && this.flashSupported) {
            CameraManager mCameraManager = (CameraManager) this.mContext.getSystemService(Context.CAMERA_SERVICE);
            try {
                mCameraManager.setTorchMode(mCameraIDList[0], false);
            } catch (CameraAccessException e) {
                Intent intent = new Intent(InputOutputReceiver.ACTION_OUTPUT);
                intent.putExtra(InputOutputReceiver.TEXT, e.toString());
                mContext.sendBroadcast(intent);
                return;
            }
            this.updateStatus(false);
        }
    }
}
项目:PGMacTips    文件:CameraMediaUtilities.java   
/**
 * Checks if user has front facing camera.
 * @param context Context used to check
 * @return 0 For front facing, 1 for back facing, -1 for if it does not have front facing at all
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static int doesUserHaveFrontFacingCamera(Context context) {

    if(Build.VERSION.SDK_INT >= 21) {
        try {
            CameraManager cManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            for (int j = 0; j < cManager.getCameraIdList().length; j++) {
                String[] cameraId = cManager.getCameraIdList();
                CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId[j]);
                int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (cOrientation == CameraCharacteristics.LENS_FACING_FRONT)
                    return j;
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    return -1; // No front-facing camera found
}
项目:AndroidStudyDemo    文件:CameraTestActivity.java   
@TargetApi(23)
private void initData() {
    mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    mTorchCallback = new CameraManager.TorchCallback() {
        @Override
        public void onTorchModeChanged(String cameraId, boolean enabled) {
            super.onTorchModeChanged(cameraId, enabled);
            mShowTorchModeTV.setText("Camera:" + cameraId + " TorchMode change :" + enabled);
        }

        @Override
        public void onTorchModeUnavailable(String cameraId) {
            super.onTorchModeUnavailable(cameraId);
        }
    };
    try {
        mCameraIdList = mCameraManager.getCameraIdList();
    } catch (CameraAccessException e) {
        mCameraIdList = null;
        e.printStackTrace();
    }
    // 注册回调监听
    mCameraManager.registerTorchCallback(mTorchCallback, new Handler());
}
项目:MoleMapperAndroid    文件:LollipopCameraFragment.java   
@Override
public void onImageAvailable(ImageReader reader)
{
    Activity activity = getActivity();

    if(null == mTextureView || null == mPreviewSize || null == activity)
    {
        return;
    }

    try
    {
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraId);

        mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(),
                getJpegOrientation(characteristics, rotation)));
    }
    catch(CameraAccessException e)
    {
        LogExt.e(getClass(), e);
    }
}
项目:SimpleSmsRemote    文件:CameraUtils.java   
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static List<MyCameraInfo> GetAllCameras2(Context context) throws Exception {
    List<MyCameraInfo> cameras = new ArrayList<>();

    CameraManager cameraManager =
            (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);

    for (String cameraId : cameraManager.getCameraIdList()) {
        CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
        MyCameraInfo cameraInfo = MyCameraInfo.CreateFromCameraCharacteristics(cameraId,
                characteristics);
        cameras.add(cameraInfo);
    }

    return cameras;
}
项目:AudioVideo    文件:Cam2Fragment.java   
private void openCamera() {

        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);

        Log.d(TAG, "openCamera Start");
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            try {
                cameraId = manager.getCameraIdList()[0];

                // setup the camera perview.  should wrap this in a checkpermissions, which studio is bitching about
                // except it has been done before this fragment is called.
                manager.openCamera(cameraId, mStateCallback, null);

            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        } else {
            Log.e(TAG, "Don't have permission to camera!");
        }
        Log.d(TAG, "openCamera End");
    }
项目:Snapmatic-Life    文件:CameraHelper.java   
@SuppressLint("NewApi")
public static  int getCamerasCount(Context ctx)
{
    int count = 0;

    if(Build.VERSION.SDK_INT >= 21)
    {
        CameraManager manager = (CameraManager) ctx.getSystemService(Context.CAMERA_SERVICE);
        try
        {
            count = manager.getCameraIdList().length;

        } catch ( CameraAccessException e)
        {
            LogHelper.logx(e);
        }

    }
    else
    {
        count = Camera.getNumberOfCameras();
    }


    return count;
}
项目:Snapmatic-Life    文件:CameraHelper.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static  boolean isFrontCamera(Context ctx, String cameraId)
{

    boolean isFront = false;

    CameraManager manager = (CameraManager) ctx.getSystemService(Context.CAMERA_SERVICE);
    try
    {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

        if (characteristics.get(CameraCharacteristics.LENS_FACING)
                == CameraCharacteristics.LENS_FACING_FRONT)
        {
            isFront = true;
        }

    } catch (CameraAccessException e)
    {
        LogHelper.logx(e);
    }

    return isFront;
}
项目:Camera2    文件:OneCameraManager.java   
/**
 * Creates a new camera manager that is based on Camera2 API, if available,
 * or otherwise uses the portability API.
 *
 * @throws OneCameraException Thrown if an error occurred while trying to
 *             access the camera.
 */
private static OneCameraManager create(CameraActivity activity) throws OneCameraException {
    DisplayMetrics displayMetrics = getDisplayMetrics(activity);
    CameraManager cameraManager = null;

    try {
        cameraManager = ApiHelper.HAS_CAMERA_2_API ? (CameraManager) activity
                .getSystemService(Context.CAMERA_SERVICE) : null;
    } catch (IllegalStateException ex) {
        cameraManager = null;
        Log.e(TAG, "Could not get camera service v2", ex);
    }
    if (cameraManager != null && isCamera2Supported(cameraManager)) {
        int maxMemoryMB = activity.getServices().getMemoryManager()
                .getMaxAllowedNativeMemoryAllocation();
        return new com.android.camera.one.v2.OneCameraManagerImpl(
                activity.getAndroidContext(), cameraManager, maxMemoryMB,
                displayMetrics, activity.getSoundPlayer());
    } else {
        return new com.android.camera.one.v1.OneCameraManagerImpl();
    }
}
项目:Camera2    文件:OneCameraManager.java   
/**
     * Returns whether the device fully supports API2
     *
     * @param cameraManager the Camera2 API manager.
     * @return If this device is only emulating Camera2 API on top of an older
     *         HAL (such as the Nexus 4, 7 or 10), this method returns false. It
     *         only returns true, if Camera2 is fully supported through newer
     *         HALs.
     * @throws OneCameraException Thrown if an error occurred while trying to
     *             access the camera.
     */
    private static boolean isCamera2Supported(CameraManager cameraManager)
            throws OneCameraException {
        if (!ApiHelper.HAS_CAMERA_2_API) {
            return false;
        }
//        try {
//            String[] cameraIds = cameraManager.getCameraIdList();
//            if (cameraIds.length == 0) {
//                throw new OneCameraException("Camera 2 API supported but no devices available.");
//            }
//            final String id = cameraIds[0];
//            // TODO: We should check for all the flags we need to ensure the
//            // device is capable of taking Camera2 API shots. For now, let's
//            // accept all device that are either 'partial' or 'full' devices
//            // (but not legacy).
//            return cameraManager.getCameraCharacteristics(id).get(
//                    CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
//                != CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
//        } catch (CameraAccessException ex) {
//            Log.e(TAG, "Could not access camera to determine hardware-level API support.");
//            return false;
//        }
        return false;
    }
项目:PlexPy-Remote    文件:ServerQRScannerActivity.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void scanCode() {

    try {
        CameraManager manager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds = manager.getCameraIdList();
        for (int i = 0; i < cameraIds.length; i++) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[i]);
            if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) {
                IntentIntegrator integrator = new IntentIntegrator(this);
                integrator.setCameraId(i);
                integrator.initiateScan();
            }
        }
    } catch (CameraAccessException e) {
    }

}
项目:android_camera2_api_video_app    文件:Camera2VideoImageActivity.java   
private void connectCamera() {
    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) ==
                    PackageManager.PERMISSION_GRANTED) {
                cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
            } else {
                if(shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA)) {
                    Toast.makeText(this,
                            "Video app required access to camera", Toast.LENGTH_SHORT).show();
                }
                requestPermissions(new String[] {android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO
                }, REQUEST_CAMERA_PERMISSION_RESULT);
            }

        } else {
            cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
项目:privacy-friendly-torchlight    文件:CameraMarshmallow.java   
@Override
@TargetApi(Build.VERSION_CODES.M)
public void init(Context context) {
    mContext = context;
    mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);

    try {
        for(final String cameraId : mCameraManager.getCameraIdList()){
            CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
            int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
            if(cOrientation == CameraCharacteristics.LENS_FACING_BACK){
                mCameraID= cameraId;
            }
        }


    } catch (CameraAccessException e) {
        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

}
项目:AARemu    文件:PreviewCamera.java   
@Override
@SuppressLint({"NewApi", "MissingPermission, UseCheckPermission"})
@SuppressWarnings({"ResourceType"})
public void startPreview(boolean isFlashOn)
//-----------------------
{
   if (cameraWidth < 0 || cameraHeight < 0)
      return;
   this.isFlashOn = isFlashOn;
   CameraManager manager = (CameraManager) surfaceView.getContext().getSystemService(Context.CAMERA_SERVICE);
   if (manager == null)
      return;
   try
   {
      cameraThread = new HandlerThread("CameraPreview");
      cameraThread.start();
      cameraHandler = new Handler(cameraThread.getLooper());
      manager.openCamera(cameraID, cameraStateCallback, cameraHandler);
   }
   catch (Exception e)
   {
      Log.e(LOGTAG, "", e);
      throw new RuntimeException(e);
   }
}
项目:AARemu    文件:LegacyPreviewCamera.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected String camera2Id(final int face)
//----------------------------------------
{
   try
   {
      CameraManager manager = (CameraManager) surfaceView.getContext().getSystemService(Context.CAMERA_SERVICE);
      String camList[] = manager.getCameraIdList();
      if (camList.length == 0)
         return null;
      CameraCharacteristics characteristics = null;
      for (String cameraID : camList)
      {
         characteristics = manager.getCameraCharacteristics(cameraID);
         Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
         if (facing == null) continue;
         if (face == facing)
            return cameraID;
      }
   }
   catch (Exception e)
   {
      return null;
   }
   return null;
}
项目:CameraFragment    文件:Camera2Manager.java   
@Override
public void initializeCameraManager(ConfigurationProvider configurationProvider, Context context) {
    super.initializeCameraManager(configurationProvider, context);

    this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);

    final WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    final Display display = windowManager.getDefaultDisplay();
    final Point size = new Point();
    display.getSize(size);
    windowSize = new Size(size.x, size.y);

    try {
        final String[] ids = manager.getCameraIdList();
        numberOfCameras = ids.length;
        for (String id : ids) {
            final CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);

            final int orientation = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (orientation == CameraCharacteristics.LENS_FACING_FRONT) {
                faceFrontCameraId = id;
                faceFrontCameraOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                frontCameraCharacteristics = characteristics;
            } else {
                faceBackCameraId = id;
                faceBackCameraOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                backCameraCharacteristics = characteristics;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error during camera init");
    }
}
项目:CameraFragment    文件:CameraHelper.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static boolean hasCamera2(Context context) {
    if (context == null) return false;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return false;
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] idList = manager.getCameraIdList();
        boolean notNull = true;
        if (idList.length == 0) {
            notNull = false;
        } else {
            for (final String str : idList) {
                if (str == null || str.trim().isEmpty()) {
                    notNull = false;
                    break;
                }
                final CameraCharacteristics characteristics = manager.getCameraCharacteristics(str);

                final int supportLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
                if (supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
                    notNull = false;
                    break;
                }
            }
        }
        return notNull;
    } catch (Throwable ignore) {
        return false;
    }
}
项目:SIGHT-For-the-Blind    文件:CameraHandler.java   
/**
 * Initialize the camera device
 */
public void initializeCamera(Context context,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    String[] camIds = {};
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.d(TAG, "Cam access exception getting IDs", e);
    }
    if (camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    String id = camIds[0];
    Log.d(TAG, "Using camera id " + id);
    // Initialize the image processor
    mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
            ImageFormat.JPEG, MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(
            imageAvailableListener, backgroundHandler);
    // Open the camera resource
    try {
        manager.openCamera(id, mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
项目:tensorflow-classifier-android    文件:CameraActivity.java   
private String chooseCamera() {
  final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
  try {
    for (final String cameraId : manager.getCameraIdList()) {
      final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

      // We don't use a front facing camera in this sample.
      final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
      if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
        continue;
      }

      final StreamConfigurationMap map =
          characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

      if (map == null) {
        continue;
      }

      useCamera2API = isHardwareLevelSupported(characteristics,
          CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL);
      LOGGER.i("Camera API lv2?: %s", useCamera2API);
      return cameraId;
    }
  } catch (CameraAccessException e) {
    LOGGER.e(e, "Not allowed to access camera");
  }

  return null;
}
项目:PXLSRT    文件:Camera2.java   
Camera2(Callback callback, PreviewImpl preview, Context context) {
    super(callback, preview);
    mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    mPreview.setCallback(new PreviewImpl.Callback() {
        @Override
        public void onSurfaceChanged() {
            startCaptureSession();
        }
    });
}
项目:android-robocar    文件:CameraOperator.java   
private void init(Context context) throws CameraAccessException {
  inSession = false;

  if (!ImageSaver.isExternalStorageWritable()) {
    Timber.e("Cannot save file, external storage is not writable.");
    return;
  }

  File root = ImageSaver.getRoot(ROBOCAR_FOLDER);
  if (root == null) {
    Timber.e("Failed to create destination folder.");
    return;
  }

  CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
  String[] cameras = manager.getCameraIdList();
  if (cameras.length == 0) {
    Timber.e("No cameras available.");
    return;
  }

  Timber.d("Default camera selected (%s), %d cameras found.",
      cameras[CAMERA_INDEX], cameras.length);

  if (ActivityCompat.checkSelfPermission(
      context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    Timber.d("Camera permission not granted yet, restart your device.");
    return;
  }

  // Debug and check for autofocus support
  dumpFormatInfo(manager, cameras[CAMERA_INDEX]);

  startBackgroundThread();
  deviceCallback = new DeviceCallback();
  manager.openCamera(cameras[CAMERA_INDEX], deviceCallback, backgroundHandler);
}
项目:hella-renderscript    文件:BaseViewfinderActivity.java   
/**
 * Attempt to initialize the camera.
 */
private void initializeCamera() {
    mCameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
    if (mCameraManager != null) {
        mCameraOps = new CameraOps(mCameraManager,
            /*errorDisplayer*/ this,
            /*readyListener*/ this,
            /*readyHandler*/ mUiHandler);
    } else {
        Log.e(TAG, "Couldn't initialize the camera");
    }
}