1 /*
2  * Copyright 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.example.android.powerprofile.cameraflashlight;
18 
19 import android.app.Activity;
20 import android.content.Context;
21 import android.hardware.camera2.CameraAccessException;
22 import android.hardware.camera2.CameraCharacteristics;
23 import android.hardware.camera2.CameraManager;
24 import android.os.Bundle;
25 
26 public class FlashlightActivity extends Activity {
27 
28     private CameraManager mCameraManager;
29     private String mCameraId;
30 
onCreate(Bundle savedInstanceState)31     protected void onCreate(Bundle savedInstanceState) {
32         super.onCreate(savedInstanceState);
33 
34         try {
35             mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
36 
37             for (String cameraId: mCameraManager.getCameraIdList()) {
38                 Boolean flashAvailable = mCameraManager.getCameraCharacteristics(cameraId).
39                         get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
40                 if (flashAvailable != null && Boolean.TRUE.equals(flashAvailable)) {
41                     mCameraId = cameraId;
42                     break;
43                 }
44             }
45         } catch (CameraAccessException e) {
46             e.printStackTrace();
47         }
48     }
49 
50     @Override
onResume()51     protected void onResume() {
52         super.onResume();
53 
54         try {
55             if (mCameraId != null) {
56                 mCameraManager.setTorchMode(mCameraId, true);
57             }
58         } catch (CameraAccessException e) {
59             e.printStackTrace();
60         }
61     }
62 
63     @Override
onPause()64     protected void onPause() {
65         super.onPause();
66 
67         try {
68             if (mCameraId != null) {
69                 mCameraManager.setTorchMode(mCameraId, false);
70             }
71         } catch (CameraAccessException e) {
72             e.printStackTrace();
73         }
74     }
75 
76 }
77