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.
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 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:
[xml]<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>[/xml]
In the IDE preview we have as result:
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:
[java]@Overridepublic 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();
}
}
[/java]
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:
// 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);
}
});
[/java]
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:
[java]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();
}[/java]
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:
[xml]<uses-feature android:name=”android.hardware.camera”/>[/xml]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:
[xml]<TextViewandroid: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″/>
[/xml]
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:
[java]// SeekbarSeekBar 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) {
}
});
[/java]
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:
[java]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();
}[/java]
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:
[java]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) {}
}
}[/java]
The source code is available @ github.
What would be the maximum frequency of strobing, and could any fine control of the frequency be implemented, I e. Synchronising with a timer to set an accurate flash rate?
I can't find Main activity.java can someone Please help
Hi Ed,
did you downalod the source code in the right way?. The MainActivity.java is here https://github.com/survivingwithandroid/Swa-app/blob/master/TorchApp/torch/src/main/java/com/survivingwithandroid/torch/MainActivity.java
so if you downloaded it from github you should have this class.
Consider that the app is developed using Android Studio.
Let me know if you still have problems.
Bye
At the moment the app isn't production ready so it should be improved. One aspect that can be improved is the light frequency. You can use a timer to set the frequency with a finer control. It could be an idea of improvement. Thx for your support!
I have created a flashlight app 'Moto Torch' specially for Moto G with the help of this tutorial.
I am not using complete code from this tutorial but some portion. Its working perfect on Android Kitkat. You can go to the link below and download this app.
http://www.techcareonline.in/2014/09/moto-torch-free-android-flashlight-app.html
Thank you so much for this tutorial.
This design is spectacular! You obviously know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to start my
own blog (well, almost…HaHa!) Great job. I really enjoyed what you
had to say, and more than that, how you presented it.
Too cool!
Can i use this tutorial code and release the app in play store?
it works only when u flashlight off then its blink otherwise when u change value of seekbar on running before off it will not working ..