0

I am an android developer , i want to on my mobile flashlight . I have Nexus5. My code is below.Any one can help me? Tell me what is missing here? I have set permissions, no error occred but not app works fine.

Main Activity.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.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.btn_switch_on);
    }else{
        btnSwitch.setImageResource(R.drawable.btn_switch_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;
    }
}

}

any my Android.manifest file is here.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.flashlight"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<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.androidhive.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>

i am posting 2nd time , i did not get solution first time. i have read many tutorials.

NadeemYousaf
  • 233
  • 1
  • 3
  • 12

4 Answers4

1

These are the permissions in Manifest. I forgot to tell you, my bad!

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

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

There are many reasons why this might not work. hasFlash is probably not the best way to check for flash. You probably want to check for FLASH_MODE_ON in addition to FLASH_MODE_TORCH. You may need to have a preview and implement the SurfaceHolder.Callback. I would probably increase android:targetSdkVersion="17" while you're at it. I just built an open source flashlight. It works on Nexus 5 if you want to look at/use the source code. Flashlight by Joe github

jbutewicz
  • 26
  • 3
  • Is there a way that we can turn on/off the flaslight using the front cameras instance parameters rather than using the back cameras? Pls assist if you can ,My question : http://stackoverflow.com/questions/26202403/how-to-turn-on-flashlight-and-front-camera-at-the-same-time-in-android – Basher51 Nov 08 '14 at 15:53
0

You have to open your camera before accessing flash light. You declared Camera but not use it. Try this.

public void cameraon() {
    cam = Camera.open();
    par = cam.getParameters();
    par.setFlashMode(Parameters.FLASH_MODE_ON);
    par.setFlashMode(Parameters.FLASH_MODE_TORCH);
    cam.setParameters(par);
    cam.startPreview();
}

public void cameraoff() {
    par.setFlashMode(Parameters.FLASH_MODE_OFF);
    cam.setParameters(par);
    cam.stopPreview();
    cam.release();
}
0

I know its late however may be it can help someone else. The reason your code does not work is that you are using the camera and media player simultaneously. if the flash gets on , your media player will stop working. Or if the media player is running then you can't get instance of camera which is required to light the Flash.

Abid
  • 126
  • 2
  • 11