Tutorial details

Android Torch App with Stroboscopic light Tutorial | App Code for Sale | Preview

Android Torch App with Stroboscopic light Tutorial | Android Tutorial

How to create a simple torch app in Android

Overview PAGE TOP

In this post, we want to describe how to create a simple torch app in Android. It is a nice example, because we can explore some Android API about Android Camera. 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 App layout PAGE TOP

The first thing we have to do is defining the 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:tools="<a href="http://schemas.android.com/tools">http://schemas.android.com/tools</a>&nbsp;android:layout_width="match_parent"<br />android:layout_height="match_parent"&nbsp;android:paddingLeft="@dimen/activity_horizontal_margin"&nbsp;android:paddingRight="@dimen/activity_horizontal_margin"&nbsp;android:paddingTop="@dimen/activity_vertical_margin"&nbsp;android:paddingBottom="@dimen/activity_vertical_margin"<br />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"
/>
<span style="font-size: 15px; line-height: 1.45em; ">...
</RelativeLayout>
</span>

In the IDE preview we have as result:

Handling Camera flash light On and Off PAGE TOP

Now we have to handle ToggleButton event. 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);<br />// Let's get the reference to the toggle<br />ToggleButton tBtn = (ToggleButton) rootView.findViewById(R.id.toggleButton);<br />tBtn.setOnCheckedChangeListener(new&nbsp;CompoundButton.OnCheckedChangeListener() {<br />@Override<br />public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {<br />Log.d("TORCH", "IS CHECKED ["+isChecked+"]");<br />turnOnOff(isChecked);<br />}<br />});

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<em>MODE</em>TORCH);
if (!on)
camParams.setFlashMode(Camera.Parameters.FLASH<em>MODE</em>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.FLASHMODETORCH and Camera.Parameters.FLASHMODEOFF.

Android Manifest.xml PAGE TOP

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:

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

Implementing stroboscopic light PAGE TOP

The last step is implementing the stroboscopic light. 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<br />SeekBar skBar = (SeekBar) rootView.findViewById(R.id.seekBar);<br />skBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {<br />@Override<br />public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
freq = progress;<br />}<br />@Override<br />public void onStartTrackingTouch(SeekBar seekBar) {<br />}<br />@Override<br />public void onStopTrackingTouch(SeekBar seekBar) {<br />}<br />});

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

  • The source code will be available @github.

Reference PAGE TOP

http://www.javacodegeeks.com/2014/02/android-torch-app-with-stroboscopic-light-tutorial.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.