In this article, we will explain how to create a free flashlight app for Android. This tutorial is part of Learn By Doing tutorial series, where we will show you how to create simple Android apps. This will be a hand’s on experience for beginners in the Android Development. After following this tutorial, you can create the best flashlight app for Android phones and distribute it through Google play.
Creating a New Project
Please follow the steps:
- Open Android Studio and create a new project by going to File => New => New Project. Enter the Application Name as
LedFlashLight
and your company domain name. (We have used our company domain, i.e., androidtutorialpoint.com
. Similarly, you can use yours.) - Click Next and choose Minimum SDK. We have kept the default setting and click Next.
- Choose Empty Activity and click next.
- In the next screen, enter Activity Name as
FlashLightActivity
and remember to check the Generate Layout Button and then click Finish.
Gradle will sync the project and resolve all the dependencies.
Adding Permissions to Use Camera and FlashLight
Open your AndroidManifest.xml file and add the following permissions:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.flash" />
These uses-permissions
tag tells the Android OS that our app will require access to CAMERA
and FLASHLIGHT
. Similarly uses-feature
tells what features will be used in the app.
The Led Flash Light Application will only work in Portrait mode, so add the following in activity
tag.
android:screenOrientation="portrait"
The complete AndroidManifest.xml will be as follows:
AnroidManifest.xml
="1.0"="utf-8"
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidtutorialpoint.ledflashlight" >
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.flash" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".FlashLightActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Apart from the package name, everything should be the same for you.
Generate Application Layout
Open activity_flash_light.xml and add the following code:
="1.0"="utf-8"
<LinearLayout 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:orientation="vertical"
tools:context="com.camera2.MainActivity"
android:background="#000"
android:gravity="center">
<ImageButton
android:layout_gravity="center"
android:id="@+id/button_on_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:src="@drawable/off"/>
</LinearLayout>
We are using an ImageButton
. When the user presses this button, the Led Flash Light will be toggled.
Adding the Functionality
Open FlashLightActivity.java and declare the following variables.
FlashLightActivity.java
package com.androidtutorialpoint.ledflashlight;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
public class FlashLightActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private Boolean isTorchOn;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FlashLightActivity", "onCreate()");
setContentView(R.layout.activity_flash_light);
mTorchOnOffButton = (ImageButton) findViewById(R.id.button_on_off);
isTorchOn = false;
Here, we are just declaring the variables and in the onCreate()
method, we are setting the layout for the activity. We are also referencing the mTorchOnOffButton Button
from the layout. We will talk more about this in a while. Here we are using Camera2
API since Camera
API is deprecated in Android now.
We need to detect whether the device has a Flash Light or not. In case the device doesn’t have support for flashlight, we have to alert the user through an alert message.
Add the following code below the above code in the FlashActivity
activity.
FlashLightActivity
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(FlashLightActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
});
alert.show();
return;
}
If your phone doesn’t support camera flash, you will get the following error.
On pressing the OK button, the app will close.
Next, we add the code to the onCreate()
method to get the CameraManager
object. Then, we set the OnClickListener()
for the on/off button for our Led Flash Light Application.
In the OnClickListener()
, we check whether the torch is currently on or off, then we call the turnOffFlashLight()
to turn flash off in case the torch is already on and turnOnFlashLight()
to turn flash on in case the torch is currently off.
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Next, we add the turnOffFlashLight()
and turnOnFlashLight()
methods for turning the Flash Off and On respectively. We will also add a method playOnOffSound
to give the sound effect of clicking a button.
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void playOnOffSound(){
mp = MediaPlayer.create(FlashLightActivity.this, R.raw.flash_sound);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
In the turnOffFlashLight()
, we turn off the Led Torch by setting
mCameraManager.setTorchMode(mCameraId, false);
. Similarly, in the turnOnFlashLight()
, we turn on the flashlight programmatically by setting mCameraManager.setTorchMode(mCameraId, true);
.
In the playOnOffSound()
, we use create()
method of the MediaPlayer
class to play the click sound.
At last, override the Activity Lifecycle methods by adding the following code. When the App is minimized by user, we will turnOff
the Flash and as soon as the user returns to the App, the Flash Light will resume if it was on earlier.
@Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}
@Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}
@Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}
Now, run the app on an Actual Device, turn on flashlight and then use your own brightest flashlight app to find your stuff in the dark. You can download the Android flashlight app source code by clicking on the Download Now button at the top. You can also download the torch light apk by clicking on the Download APK above.