Home » Android » android – Turn ON/OFF flashlight in zxing fragment lib

android – Turn ON/OFF flashlight in zxing fragment lib

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have implemented Zxing barcode scanning library in my application. I have used following library:
https://code.google.com/p/barcodefraglibv2/
I want to turn ON/OFF the flash light on click of a button when scanning but I am not able to do this. Library has exposed one function for the same but it is not working.

Code used is:
fragment = (BarcodeFragment)getSupportFragmentManager().findFragmentById(R.id.sample);
fragment.getCameraManager().setTorch(true);

Provide me any refrence code by which I can turn ON/OFF flashlight.

How to&Answers:

You should go through the sample app in zxing-android-embedded library, there you can find CustomScannerActivity class which shows how to switch ON and OFF flash light
below is the link:

https://github.com/journeyapps/zxing-android-embedded/blob/master/sample/src/main/java/example/zxing/CustomScannerActivity.java

Code sample from above link:

public class CustomScannerActivity extends Activity implements
    DecoratedBarcodeView.TorchListener {

private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
private Button switchFlashlightButton;

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

    barcodeScannerView = (DecoratedBarcodeView)findViewById(R.id.zxing_barcode_scanner);
    barcodeScannerView.setTorchListener(this);

    switchFlashlightButton = (Button)findViewById(R.id.switch_flashlight);

    // if the device does not have flashlight in its camera,
    // then remove the switch flashlight button...
    if (!hasFlash()) {
        switchFlashlightButton.setVisibility(View.GONE);
    }

    capture = new CaptureManager(this, barcodeScannerView);
    capture.initializeFromIntent(getIntent(), savedInstanceState);
    capture.decode();
}

@Override
protected void onResume() {
    super.onResume();
    capture.onResume();
}

@Override
protected void onPause() {
    super.onPause();
    capture.onPause();
}

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

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    capture.onSaveInstanceState(outState);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}

/**
 * Check if the device's camera has a Flashlight.
 * @return true if there is Flashlight, otherwise false.
 */
private boolean hasFlash() {
    return getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}

public void switchFlashlight(View view) {
    if (getString(R.string.turn_on_flashlight).equals(switchFlashlightButton.getText())) {
        barcodeScannerView.setTorchOn();
    } else {
        barcodeScannerView.setTorchOff();
    }
}

@Override
public void onTorchOn() {
    switchFlashlightButton.setText(R.string.turn_off_flashlight);
}

@Override
public void onTorchOff() {
    switchFlashlightButton.setText(R.string.turn_on_flashlight);
} 
}

Answer:

You can use this:

public void flashON(View v) {
        mScannerView.setFlash(true);
    }

    public void flashOFF(View v){
        mScannerView.setFlash(false);
    }

Where flashON and flashOFF are 2 imageButtons.
This is xml:

 <me.dm7.barcodescanner.zxing.ZXingScannerView
        android:id="@+id/zxscan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </me.dm7.barcodescanner.zxing.ZXingScannerView>

    <ImageButton
        android:id="@+id/FlashON"
        android:onClick="flashON"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/FlashOFF"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/FlashOFF"
        android:layout_marginEnd="60dp"
        android:layout_marginRight="60dp"
        android:src="@drawable/flashon" />

    <ImageButton
        android:id="@+id/FlashOFF"
        android:onClick="flashOFF"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/NumeEchip"
        android:layout_marginEnd="13dp"
        android:layout_marginRight="13dp"
        android:src="@drawable/flashoff" />

Answer:

You need to add these the following permission and feature to your Manifest in order to control the flash.

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

Here’s a sample code –

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ToggleButton;

/**
 * @author Prabu 
 * July 30 2013
 * @version 1.0
 * 
 */
public class FlashlightActivity extends Activity {
 private Camera camera;
 private ToggleButton button;
 private final Context context = this;
 /**
  * @see android.app.Activity#onStop()
  */
 @Override
 protected void onStop() {
  super.onStop();
  if (camera != null) {
   camera.release();
  }
 }

 /**
  * @see android.app.Activity#onCreate(android.os.Bundle)
  */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.flashlight);
  button = (ToggleButton) findViewById(R.id.togglebutton);

  final PackageManager pm = context.getPackageManager();
  if(!isCameraSupported(pm)){
   AlertDialog alertDialog = new AlertDialog.Builder(context).create();
   alertDialog.setTitle("No Camera");
      alertDialog.setMessage("The device's doesn't support camera.");
      alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
          public void onClick(final DialogInterface dialog, final int which) { 
           Log.e("err", "The device's doesn't support camera.");
          }
       });
   alertDialog.show();
  }
  camera = Camera.open();
 }
 public void onToggleClicked(View view) {
  PackageManager pm=context.getPackageManager();
  final Parameters p = camera.getParameters();
  if(isFlashSupported(pm)){
   boolean on = ((ToggleButton) view).isChecked();
   if (on) {
    Log.i("info", "torch is turn on!");
    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
    camera.setParameters(p);
    camera.startPreview();
   } else {
    Log.i("info", "torch is turn off!");
    p.setFlashMode(Parameters.FLASH_MODE_OFF);
    camera.setParameters(p);
    camera.stopPreview();
   }
  }else{
   button.setChecked(false);
   AlertDialog alertDialog = new AlertDialog.Builder(context).create();
   alertDialog.setTitle("No Camera Flash");
      alertDialog.setMessage("The device's camera doesn't support flash.");
      alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
          public void onClick(final DialogInterface dialog, final int which) { 
           Log.e("err", "The device's camera doesn't support flash.");
          }
       });
   alertDialog.show();
  }
 }
 /**
  * @param packageManager
  * @return true <b>if the device support camera flash</b><br/>
  * false <b>if the device doesn't support camera flash</b>
  */
 private boolean isFlashSupported(PackageManager packageManager){ 
  // if device support camera flash?
  if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
   return true;
  } 
  return false;
 }

 /**
  * @param packageManager
  * @return true <b>if the device support camera</b><br/>
  * false <b>if the device doesn't support camera</b>
  */
 private boolean isCameraSupported(PackageManager packageManager){
  // if device support camera?
  if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
   return true;
  } 
  return false;
 }
}

For full source – > Visit Here

Answer:

open CameraManager activity from zxing source code and paste follwing code in startPreview(). before camera.startPreview()

 Camera.Parameters p;
 p = camera.getParameters();
 p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
 camera.setParameters(p);

Answer:

In https://github.com/zxing/zxing/blob/0cf3b9be71680f50c90a71ca26ce0d33664b0dd6/android/src/com/google/zxing/client/android/CaptureActivity.java you can see:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
      case KeyEvent.KEYCODE_VOLUME_DOWN:
        cameraManager.setTorch(false);
        return true;
      case KeyEvent.KEYCODE_VOLUME_UP:
        cameraManager.setTorch(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
  }

Answer:

If you use flashlight and then you want to open camera the flashlight is disabled and get error. Because now you have to use the flashlight feature of your camera. So you can close flashlight and open the camera’s flashlight. But only you want to use only the camera’s flashlight, it’s simple.

ZXingScannerView mScannerView;
qrcode_btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      mScannerView = new ZXingScannerView(ctx);
      contentFrame.addView(mScannerView);
      mScannerView.setResultHandler(ActivityMain.this);
      mScannerView.startCamera();
      mScannerView.setFlash(true);
   }
}

If you open flashlight before ZXing, you have to close flashlight before ZXing.

flashLightOff();
public void flashLightOff() {
   CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
   try {
      boolean flashAvailable = cameraManager.getCameraCharacteristics("0").get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
   } catch (CameraAccessException e) {
      e.printStackTrace();
   }

   try {
      String cameraId = cameraManager.getCameraIdList()[0];
      cameraManager.setTorchMode(cameraId, false);
      flashLightStatus = false;
      flashlight.setColorFilter(ContextCompat.getColor(context, R.color.grey_dark));
   } catch (CameraAccessException e) {
   }
}