0

I want turn on the Android flash for 50 miliseconds, but I cannot seem to get it to work. The debugger will run through the code with no errors, but the camera will not turn on. I have tried stopping on the await command to see if the time was too short, but I still cannot get the camera to turn on. I am confused because I have see similar code in multiple tutorials. The only difference is that mine is not running on the main activity.

Manifest:

<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" />

<!-- Unrelated code -->
<activity android:name="SyncActivity"
            android:label="@string/app_name" >
</activity>

Code:

if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
    CountDownLatch latch = new CountDownLatch(1);
    Camera androidCamera = Camera.open();
    Camera.Parameters p = androidCamera.getParameters();
    p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
    androidCamera.setParameters(p);
    //Flash and then turn off
    androidCamera.startPreview();
    latch.await(50, TimeUnit.MILLISECONDS); 
    androidCamera.stopPreview();
    androidCamera.release();

} else {
    throw new Exception("Cannot access Android Flash");
}
Soatl
  • 10,224
  • 28
  • 95
  • 153

1 Answers1

0

Found the answer here.

Code:

SurfaceView preview = (SurfaceView) findViewById(R.id.PREVIEW);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
Camera mCamera = Camera.open();
mCamera.setPreviewDisplay(mHolder);

// Turn on LED  
Parameters params = mCamera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(params);      
mCamera.startPreview();

...

// Turn off LED
Parameters params = mCamera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);
mCamera.stopPreview();
mCamera.release();

public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {}

public void surfaceCreated(SurfaceHolder holder) {
    mHolder = holder;
    mCamera.setPreviewDisplay(mHolder);
}

public void surfaceDestroyed(SurfaceHolder holder) {
    mCamera.stopPreview();
    mHolder = null;
}

<SurfaceView
    android:id="@+id/PREVIEW"
    android:layout_width="1dip"
    android:layout_height="1dip"/>
Community
  • 1
  • 1
Soatl
  • 10,224
  • 28
  • 95
  • 153