In that tutorial, you are going to learn how to create a Torch Flashlight application for Android with Android Studio. A lot of tutorials ex...

Torch Light App tutorils in android studio

23:26 2 Comments

In that tutorial, you are going to learn how to create a Torch Flashlight application for Android with Android Studio. A lot of tutorials exist to teach you to use the flashlight of your device via the Camera API but this API is now deprecated since Android API level 25.
So, to be up to date we are going to use the Camera2 API in this tutorial. Note that you can discover this tutorial in video on YouTube :

Creating the User Interface

To start, we are going to create the user interface of our Torch Flashlight Application for Android. We will have one image view to display an ON / OFF switcher image. Then, a button to enable the camera permissions to use the flashlight on the Android device..

Activity_Main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/background">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_names"
        android:textColor="@color/Whit"
        android:textSize="28sp"
        android:gravity="center_horizontal|center_vertical"
        android:textStyle="bold" />

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal|center_vertical">
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical"
          android:layout_weight="1">

      </LinearLayout>
    <ImageButton
        android:id="@+id/Switch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/background"
        android:src="@drawable/off" />
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical"
      android:layout_weight="1"
      android:gravity="bottom|right">
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="This app devloped by neo-istone"
          android:textStyle="bold"
          android:textSize="14sp"
          android:textColor="#fff"/>
  </LinearLayout>
</LinearLayout>
</LinearLayout>



Updating the Android Manifest

Then, we are going to add the CAMERA permission in the android manifest and we also define the fact that we use the camera in our application :

Updating the Gradle Build File

To use the Camera2 API with no warnings on Android Studio, we are going to set the minimum Android SDK version to 23 in the Gradle Build File :

Writing the Java Code

Now, it’s time to write the Java code of the Main Activity. First, we declare a constant for the CAMERA_REQUEST request index used to request camera permissions. Then, we declare properties for the enable button and for the image view. We define a flashlight status Boolean which will indicate us if the flashlight is on or off.
In the onCreate method, we get references for the ImageView and for the button. We check if the device has a camera. We check also if the camera permission has already been granted by the user for the application. We manage the state of the button and the imageview according the camera permission authorization. We install an OnClickListener on the enable button. When the user will click on this button we will request permission for the Camera permission with the Camera Request id in parameter.

We set an OnClickListener on the ImageView. When a user will click on the image view, first we check if the device has camera flash. If no, we display a message to alert the user. Otherwise, we turn off the light if needed by calling the flashLightOff method. And we turn on the light if needed by calling the flashLightOn method.


 <?xml version="1.0" encoding="utf-8"?>
Switch.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    if (hasCameraFlash) {
      if (flashLightStatus)
        flashLightOff();
      else
        flashLightOn();
    } else {
      Toast.makeText(MainActivity.this, "No flash available on your device",
            Toast.LENGTH_SHORT).show();
    }
  }
});

Now, we write the flashLightOn method. We get the camera service. Usually, the front camera is at the first position. With the camera manager we call the set torch mode method with cameraId in parameter to enable it. We set the flashlight status to true and we change the image in the image view.


@TargetApi(Build.VERSION_CODES.M)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void flashLightOn() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, true);
            flashLightStatus = true;
            Switch.setImageResource(R.drawable.on);
        } catch (CameraAccessException e) {
            Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
        }
    }

Now, we write the flashLightOff method. We get the camera service. Usually, the front camera is at the first position. With the camera manager we call the set torch mode method with cameraId in parameter to enable it. We set the flashlight status to true and we change the image in the image view.

@RequiresApi(api = Build.VERSION_CODES.M)
    private void flashLightOff() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, false);
            flashLightStatus = false;
            Switch.setImageResource(R.drawable.off);
        } catch (CameraAccessException e) {
            Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
        }
    }
Finally, we override the onRequestPermissionsResult method. We check if the user has granted the camera permission. If yes, we disable the enable button and we change the text of the button to display a camera enabled message. Then, we enable the ImageView to let the user light up the Flashlight of their device :


MainActivity.java 

Full code:

package light.flash.istone.neo.com.flashlightapp;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    ImageButton Switch;
    private static final int CAMERA_REQUEST = 50;
    private boolean flashLightStatus = false;



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

        final boolean hasCameraFlash = getPackageManager().
                hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        boolean isEnabled = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;
        ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, CAMERA_REQUEST);
        Switch = (ImageButton) findViewById(R.id.Switch);
    Switch.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View view) {
                if (hasCameraFlash) {
                    if (flashLightStatus)
                        flashLightOff();
                    else
                        flashLightOn();
                } else {
                    Toast.makeText(MainActivity.this, "No flash available on your device",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.M)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void flashLightOn() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, true);
            flashLightStatus = true;
            Switch.setImageResource(R.drawable.on);
        } catch (CameraAccessException e) {
            Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void flashLightOff() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, false);
            flashLightStatus = false;
            Switch.setImageResource(R.drawable.off);
        } catch (CameraAccessException e) {
            Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode) {
            case CAMERA_REQUEST :
                if (grantResults.length > 0  &&  grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Switch.setEnabled(true);
                } else {
                    Toast.makeText(MainActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

Testing our Torch Flashlight Application

Now, it’s time to test our Torch Flashlight Application. You should obtain the following result :


2 comments:

  1. If possible i want to visit in this site daily i think this site is very helpful for me

    ReplyDelete