Introduction
In this article, I aim to demonstrate the creation of an Android Torch Application in the simplest manner possible. The code is simple and quite easy to understand even for a novice.
Background
The interface of the app consists of a single ImageButton
control whose image toggles to represent the On and Off states. The following is the layout code (activity_main.xml):
="1.0"="utf-8"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.example.azim.mytorch.MainActivity">
<ImageButton android:id="@+id/btnOnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/start" />
</LinearLayout>
The following lines are required in the AndroidManifest.xml file to enable the use of camera in the app.
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.Camera"/>
Using the Code
The following function can be created to check if the camera flash feature is supported by our device:
private boolean isFlashSupported()
{
return getApplicationContext().getPackageManager().hasSystemFeature
(PackageManager.FEATURE_CAMERA_FLASH);
}
Following is the code of the onClick()
method of the ImageButton
:
public void onClick(View view)
{
if(isFlashSupported())
{
if(!isOn)
{
camera=Camera.open();
params=camera.getParameters();
params.setFlashMode(params.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
btnOnOff.setImageResource(R.drawable.stop);
Toast.makeText(getBaseContext(),"Torch turned on",Toast.LENGTH_SHORT).show();
}
else
{
params=camera.getParameters();
params.setFlashMode(params.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.release();
camera=null;
btnOnOff.setImageResource(R.drawable.start);
Toast.makeText(getBaseContext(),"Torch turned off",Toast.LENGTH_SHORT).show();
}
isOn=!isOn;
}
else
{
Toast.makeText(getBaseContext(),"Sorry your device does not support flash light",
Toast.LENGTH_SHORT).show();
}
}
The above code uses a boolean
variable isOn
to check the current state of the camera. The setFlashMode()
method of the Camera.Parameters
class is used to change the state of the camera. The setImageResource()
method of the ImageButton
class is used to change the image on the button.
Points of Interest
I hope this article will be helpful in understanding the working of the torch app of Android.