Skip to main content

Android Flashlight Application Tutorial

In this Android tutorial let us learn about how to create a nice small Android app which will help double your Android device as a flashlight too. It would be handy to have this flashlight app in our Android phone. Instead of downloading an app from the Google play store, wouldn’t it be nice if we develop it ourselves.



This is a simple app, all we are going to do is control the camera’s flashlight. In our app we will have a toggle switch to On and Off the camera flash. That’s it.

Step 1: Permission to use Camera


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.mrbrown.flashlight">



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

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



    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.mrbrown.flashlight.MainActivity"
            android:label="@string/app_name" 
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



Step 2: Flashlight Control Layout

The layout will have one toggle switch which will control the flashlight on and off state. We will use two different image for on and off state. 


<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:background="@drawable/radial_background"

    tools:context=".MainActivity" >



    <ImageButton
        android:id="@+id/btnSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dip"
        android:background="@null"
        android:contentDescription="@null"
        android:src="@drawable/on" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dip"
        android:gravity="center"
        android:padding="15dip"
        android:text="Developed by Mr Brown\ne-mail:arnoldbrown009@gmail.com"
        android:textColor="#3b3b3b"
        android:textSize="13dip" />

</RelativeLayout>



Step 3: Android Activity

Important steps in the activity are,
  • check if camera is present in the device before proceeding
  • Instantiate Camera and get its parameters
  • Toggle the Camera’s flashlight state using its parameter FlashMode (FLASH_MODE_TORCH | FLASH_MODE_OFF)

public class MainActivity extends Activity {



ImageButton btnSwitch;



private Camera camera;

private boolean isFlashOn;

private boolean hasFlash;
Parameters params;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

/*
* First check if device is supporting flashlight or not
*/
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}

// get the camera
getCamera();
// displaying button image
toggleButtonImage();
/*
* Switch button click event to toggle flash on/off
*/
btnSwitch.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}

/*
* Get the camera
*/
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}

/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}

}

/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Playing sound
* will play button toggle sound on flash on / off
* */
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.release();
            }
        }); 
mp.start();
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.on);
}else{
btnSwitch.setImageResource(R.drawable.off);
}
}

@Override
protected void onDestroy() {
super.onDestroy();
}

@Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}

@Override
protected void onRestart() {
super.onRestart();
}

@Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}

@Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}

@Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}

}




Image Buttons:



_________________________________________________________________
Source code for this application Flashlight.zip

                                                           Happy Coding...

Comments

  1. Flashlight is a must to have application in our smartphone and most of the smartphones will have a builtin flashlight but our Flashlight application is most advanced flashlight with multiple options.

    ReplyDelete

Post a Comment

Popular posts from this blog

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ___________________________________________________________

Set Focus on Spinner when select Item on Vertical Scroll - Android Tutorial

We may face an issue on Spinner lies on long vertical scroll, (i.e.) when selected and item from dropdown the focus moves to top of scroll. To avoid this please follow this piece of code spinner.setFocusableInTouchMode( true ); spinner.setOnFocusChangeListener( new View.OnFocusChangeListener() {     @Override     public void onFocusChange(View v, boolean hasFocus) {         if (hasFocus) {             if (spinner.getWindowToken() != null ) {                 spinner.performClick();             }         }     } });   _______________________________________________________________________________ Happy Coding...