在 zxing 片段库中打开/关闭手电筒

Posted

技术标签:

【中文标题】在 zxing 片段库中打开/关闭手电筒【英文标题】:Turn ON/OFF flashlight in zxing fragment lib 【发布时间】:2015-12-20 07:35:40 【问题描述】:

我已经在我的应用程序中实现了 Zxing 条码扫描库。我使用了以下库: https://code.google.com/p/barcodefraglibv2/ 我想在扫描时单击按钮打开/关闭闪光灯,但我无法做到这一点。图书馆已经公开了一个相同的功能,但它不起作用。

使用的代码是: 片段 = (BarcodeFragment)getSupportFragmentManager().findFragmentById(R.id.sample); fragment.getCameraManager().setTorch(true);

提供我可以打开/关闭手电筒的任何参考代码。

【问题讨论】:

使用 setTorchOn 开启,使用 setTorchOff 关闭 ***.com/questions/35993253/… 【参考方案1】:

你应该浏览zxing-android-embedded库中的示例应用程序,在那里你可以找到CustomScannerActivity类,它显示了如何打开和关闭闪光灯 以下是链接:

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

来自上述链接的代码示例:

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);
 

【讨论】:

【参考方案2】:

你可以用这个:

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


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

其中 flashON 和 flashOFF 是 2 个 ImageButton。 这是xml:

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

 <ImageButton
   android:id="@+id/FlashON"
   android:onClick="flashON"
   android:layout_
   android:layout_
   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_
   android:layout_
   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" />

【讨论】:

【参考方案3】:

您需要将以下权限和功能添加到您的清单中才能控制闪光灯。

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

这是一个示例代码 -

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;
 

获取完整源代码-> Visit Here

【讨论】:

由于 API 级别,此处不推荐使用相机参数。是否有任何其他选项可以启动相机【参考方案4】:

从 zxing 源代码中打开 CameraManager 活动并将以下代码粘贴到 startPreview() 中。在 camera.startPreview() 之前

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

【讨论】:

【参考方案5】:

在https://github.com/zxing/zxing/blob/0cf3b9be71680f50c90a71ca26ce0d33664b0dd6/android/src/com/google/zxing/client/android/CaptureActivity.java你可以看到:

@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);
  

【讨论】:

【参考方案6】:

如果您使用手电筒,然后您想打开相机,手电筒将被禁用并出现错误。因为现在您必须使用相机的手电筒功能。所以你可以关闭手电筒并打开相机的手电筒。但只要你想只用相机的手电筒,很简单。

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);
   

如果你在ZXing之前打开手电筒,你必须在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) 
   

【讨论】:

以上是关于在 zxing 片段库中打开/关闭手电筒的主要内容,如果未能解决你的问题,请参考以下文章

使用相机时如何打开/关闭手电筒?

设备屏幕关闭时如何打开手电筒?

CameraX 库如何打开/关闭手电筒?

在 QRcodeScanner React native 中打开/关闭手电筒

NodeJS - 在移动 Android/iPhone 中打开和关闭 Tourch/手电筒

如何快速打开和关闭手电筒?