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
17package com.android.ex.camera2.utils;
18
19import android.content.Context;
20import android.hardware.camera2.CameraDevice;
21import android.hardware.camera2.CameraManager;
22import android.os.Handler;
23import android.os.HandlerThread;
24import android.support.test.InstrumentationRegistry;
25
26import org.junit.After;
27import org.junit.AfterClass;
28import org.junit.Before;
29import org.junit.BeforeClass;
30
31/**
32 * Subclasses of this have an {@code mCamera} instance variable representing the first camera.
33 */
34public class Camera2DeviceTester {
35    private static HandlerThread sThread;
36
37    private static Handler sHandler;
38
39    @BeforeClass
40    public static void setupBackgroundHandler() {
41        sThread = new HandlerThread("CameraFramework");
42        sThread.start();
43        sHandler = new Handler(sThread.getLooper());
44    }
45
46    @AfterClass
47    public static void teardownBackgroundHandler() throws Exception {
48        sThread.quitSafely();
49        sThread.join();
50    }
51
52    public Context mContext = InstrumentationRegistry.getTargetContext();
53
54    private class DeviceCapturer extends CameraDevice.StateCallback {
55        private CameraDevice mCamera;
56
57        public CameraDevice captureCameraDevice() throws Exception {
58            CameraManager manager =
59                    (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
60            String id = manager.getCameraIdList()[0];
61            synchronized (this) {
62                manager.openCamera(id, this, sHandler);
63                wait();
64            }
65            return mCamera;
66        }
67
68        @Override
69        public synchronized void onOpened(CameraDevice camera) {
70            mCamera = camera;
71            notify();
72        }
73
74        @Override
75        public void onDisconnected(CameraDevice camera) {}
76
77        @Override
78        public void onError(CameraDevice camera, int error) {}
79    }
80
81    protected CameraDevice mCamera;
82
83    @Before
84    public void obtainCameraCaptureRequestBuilderFactory() throws Exception {
85        mCamera = new DeviceCapturer().captureCameraDevice();
86    }
87
88    @After
89    public void releaseCameraCaptureRequestBuilderFactory() {
90        mCamera.close();
91    }
92}
93