1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.ex.camera2.utils; 18 19 import android.content.Context; 20 import android.hardware.camera2.CameraDevice; 21 import android.hardware.camera2.CameraManager; 22 import android.os.Handler; 23 import android.os.HandlerThread; 24 25 import androidx.test.InstrumentationRegistry; 26 27 import org.junit.After; 28 import org.junit.AfterClass; 29 import org.junit.Before; 30 import org.junit.BeforeClass; 31 32 /** 33 * Subclasses of this have an {@code mCamera} instance variable representing the first camera. 34 */ 35 public class Camera2DeviceTester { 36 private static HandlerThread sThread; 37 38 private static Handler sHandler; 39 40 @BeforeClass setupBackgroundHandler()41 public static void setupBackgroundHandler() { 42 sThread = new HandlerThread("CameraFramework"); 43 sThread.start(); 44 sHandler = new Handler(sThread.getLooper()); 45 } 46 47 @AfterClass teardownBackgroundHandler()48 public static void teardownBackgroundHandler() throws Exception { 49 sThread.quitSafely(); 50 sThread.join(); 51 } 52 53 public Context mContext = InstrumentationRegistry.getTargetContext(); 54 55 private class DeviceCapturer extends CameraDevice.StateCallback { 56 private CameraDevice mCamera; 57 captureCameraDevice()58 public CameraDevice captureCameraDevice() throws Exception { 59 CameraManager manager = 60 (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE); 61 String id = manager.getCameraIdList()[0]; 62 synchronized (this) { 63 manager.openCamera(id, this, sHandler); 64 wait(); 65 } 66 return mCamera; 67 } 68 69 @Override onOpened(CameraDevice camera)70 public synchronized void onOpened(CameraDevice camera) { 71 mCamera = camera; 72 notify(); 73 } 74 75 @Override onDisconnected(CameraDevice camera)76 public void onDisconnected(CameraDevice camera) {} 77 78 @Override onError(CameraDevice camera, int error)79 public void onError(CameraDevice camera, int error) {} 80 } 81 82 protected CameraDevice mCamera; 83 84 @Before obtainCameraCaptureRequestBuilderFactory()85 public void obtainCameraCaptureRequestBuilderFactory() throws Exception { 86 mCamera = new DeviceCapturer().captureCameraDevice(); 87 } 88 89 @After releaseCameraCaptureRequestBuilderFactory()90 public void releaseCameraCaptureRequestBuilderFactory() { 91 mCamera.close(); 92 } 93 } 94