Android Torch App with Stroboscopic light – Tutorial

This post describes how to create a simple android torch app. We develop an android app using Android Camera API. We will use Android Studio as IDE to develop the app. This app will not only use the flash light but we can implement a stroboscopic light too where the frequency can be changed.

Android torch app development tutorial

We can discover how to use some basic UI components like ToggleButton and SeekBar. We want to obtain an app that looks like:

android_torch_layout_strobo

Android Torch App layout

The first thing we have to do is defining the android torch app layout. If you notice, when using Android Studio, it creates under layout directory a file named fragment_main.xml. We have to edit it and implement here our layout. At the beginning to keep things simple, we can suppose we have only the ToggleButton to turn the flash light on and off:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.survivingwithandroid.tourch.MainActivity$PlaceholderFragment">

<TextView
android:text="@string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/textView" />

<TextView
android:text="@string/torchon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp" />

<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="torchonoff"
android:id="@+id/toggleButton"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
/>
...
</RelativeLayout>

In the IDE preview we have as result:
android_torch_layout

Android Camera flash: light On and Off

Now we have to handle ToggleButton event so that the android torch app can turn and off the flash light. Looking in the source code, generated by our IDE, we have a class called MainActivity.java and there there is another inner class used to manage the fragment named PlaceHolderFragment. As we remember a fragment as a complex lifecycle that is reflected in some callback methods called by the system when the fragment moves to different states in its lifecycle. We can use onActivityCreated to get the reference to the smart phone Camera and get is parameters, so we have:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
try {
Log.d("TORCH", "Check cam");
// Get CAM reference
cam = Camera.open();
camParams = cam.getParameters();
cam.startPreview();
hasCam = true;
Log.d("TORCH", "HAS CAM ["+hasCam+"]");
}
catch(Throwable t) {
t.printStackTrace();
}

}

At line 7, we open the connection to the Camera and at line 8 we get the default parameters, we will use them later to turn the flash light on and off. At the end at line 9, we call startPreview() to start capturing preview frames.
Now we are ready to handle ToggleButton event and change the flash light according to the event triggered. We can do it in the onCreateView method, that is called when the OS gives to our fragment the chance to set its layout:

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Let's get the reference to the toggle
ToggleButton tBtn = (ToggleButton) rootView.findViewById(R.id.toggleButton);
tBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d("TORCH", "IS CHECKED ["+isChecked+"]");
turnOnOff(isChecked);
}
});

At line 1, we simply inflate the layout and look for the ToggleButton using its id. Then we handle the event when an user changes its status and we call turnOnOff method:

private void turnOnOff(boolean on) {

if (on)
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

if (!on)
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);

cam.setParameters(camParams);
cam.startPreview();
}

At line 3, we use the camera parameters to turn on and off the flash light using Camera.Parameters.FLASH_MODE_TORCH and Camera.Parameters.FLASH_MODE_OFF.

Android Manifest.xml: Android camera permission

To enable our app to use the flash light, we have to modify Android Manifest.xml so that we can declare we want to use the flash light: we have to add:

<uses-permission android:name="android.permission.CAMERA"/>

The next step is filtering the device that can install our app in the Google Play. We want that only the devices that has the flash light can install the app, so we have to add this line to the Manifest.xml:

<uses-feature android:name="android.hardware.camera"/>

Implementing stroboscopic light

The last step is implementing the stroboscopic light feature of the Android torch app. We want the user can select the light frequency, so that we will use a SeekBar. In the fragment layout we will add, then:

<TextView
android:text="@string/freq"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:layout_below="@id/toggleButton"/>

<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/seekBar"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:max="100"/>

and handle the even when user moves the progress level. As we did before for the ToggleButton, we implement an event listener in the onCreateView method:

// Seekbar
SeekBar skBar = (SeekBar) rootView.findViewById(R.id.seekBar);
skBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
freq = progress;
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});

where at line 5 we get the current level. We have to modify the turnOnOff method because if we want to strobo light we have to start a thread that turns on and off the light:

private void turnOnOff(boolean on) {

if (on) {
if (freq != 0) {
sr = new StroboRunner();
sr.freq = freq;
t = new Thread(sr);
t.start();
return ;
}
else
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
}
if (!on) {
if (t != null) {
sr.stopRunning = true;
t = null;
return ;
}
else
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}

cam.setParameters(camParams);
cam.startPreview();
}

When the user turns on the ToggleButton and the frequency is not zero then we start a new Thread that will simply turns on and off the light:

private class StroboRunner implements Runnable {

int freq;
boolean stopRunning = false;

@Override
public void run() {
Camera.Parameters paramsOn = PlaceholderFragment.this.cam.getParameters();
Camera.Parameters paramsOff = PlaceholderFragment.this.camParams;
paramsOn.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
paramsOff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
try {
while (!stopRunning) {
PlaceholderFragment.this.cam.setParameters(paramsOn);
PlaceholderFragment.this.cam.startPreview();
// We make the thread sleeping
Thread.sleep(100 - freq);
PlaceholderFragment.this.cam.setParameters(paramsOff);
PlaceholderFragment.this.cam.startPreview();
Thread.sleep(freq);
}
}
catch(Throwable t) {}
}
}

The source code is available @ github.

6 Comments

  1. Bob Builder March 24, 2014
  2. Ed March 27, 2014
  3. survivingwithandroid March 27, 2014
  4. survivingwithandroid March 27, 2014
  5. Faizan Ansari September 19, 2014

Add Comment