Recipe 9.6 Switching on the Flashlight
Along with the built-in cameras that most Android devices offer, a flashlight is usually included next to the camera on the back of the device. This recipe shows you how to activate the flashlight of your camera.
Solution
To activate the flashlight on your Android device, you first need to declare two permissions:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
You also need to have a SurfaceView in your UI to display the preview of images taken with the camera:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn On Flash"
android:onClick="TurnOn"/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn Off Flash"
android:onClick="TurnOff"/>
<SurfaceView
android:id="@+id/surface1"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</LinearLayout>
The SurfaceView view provides a dedicated drawing surface to display the images captured by your camera.
In your activity, you also need to implement ...
Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.