Skip to main content

How to create a flash light on Android

I always wonder the use of a flash light on a phone. This simple app is more useful than anything. So here is the code to build a flashlight app,

MainActivity.java

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
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.imageflash);
 
     
        // 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;
        }
        getCamera();
    // 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;
            }      
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;         
        }
 
    }
    // Turning Off flash
    private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }    
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;         
         
        }
    }
    @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 onStop() {
        super.onStop();
         
        // on stop release the camera
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }
 
}

Activity_main_layout.xml


<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.flashlight.MainActivity$PlaceholderFragment" >
   <ImageButton
       android:id="@+id/imageflash"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:src="@drawable/ic_launcher"
       android:layout_centerInParent="true"/>
</RelativeLayout>


Comments

Popular posts from this blog

Server communication in Android

In Android we can communicate with server using HTTP request methods for getting some details from the server.We use RESTful service.Mainly we use two types of HTTP request HTTP GET(),HTTP POST() methods. In some case we have to give some values to the server for fetching some informations, then we use commonly HTTP POST() and if we simply want to request for some datas we use HTTP GET(). Lets see HTTP POST() method. public void getResponse(String a, String b) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("URL"); //here write the url List < NameValuePair > nameValueList = new ArrayList < NameValuePair > (2); nameValueList.add(new BasicNameValuePair("keyword", a)); nameValueList.add(new BasicNameValuePair("keyword", b)); try { httppost.setEntity(new UrlEncodedFormEntity(nameValueList)); HttpResponse response = httpclient.execute(httppost); Log.i(...

How to record and save a video in Android

Let's record a video :). Check the code snippet. First need to give necessary permissions. So add these permissions to AndroidManifest.xml   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   <uses-permission android:name="android.permission.RECORD_AUDIO" /> MainActivity.java import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { Button btn_record; pu...