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.InjectContext;
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    @InjectContext
53    public Context mContext;
54
55    private class DeviceCapturer extends CameraDevice.StateCallback {
56        private CameraDevice mCamera;
57
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
70        public synchronized void onOpened(CameraDevice camera) {
71            mCamera = camera;
72            notify();
73        }
74
75        @Override
76        public void onDisconnected(CameraDevice camera) {}
77
78        @Override
79        public void onError(CameraDevice camera, int error) {}
80    }
81
82    protected CameraDevice mCamera;
83
84    @Before
85    public void obtainCameraCaptureRequestBuilderFactory() throws Exception {
86        mCamera = new DeviceCapturer().captureCameraDevice();
87    }
88
89    @After
90    public void releaseCameraCaptureRequestBuilderFactory() {
91        mCamera.close();
92    }
93}
94