我想在Android中以编程方式打开前闪光灯(不是相机预览)。我在谷歌上搜索了一下,但我找到的帮助把我转到了这个页面

有人有链接或示例代码吗?


当前回答

API 23或以上版本(Android M, 6.0)

打开代码

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; 
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);   //Turn ON
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

关闭代码

camManager.setTorchMode(cameraId, false);

和权限

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

额外的编辑

人们仍然在为我的答案投票,所以我决定发布额外的代码 这是我当时对这个问题的解决方案:

public class FlashlightProvider {

private static final String TAG = FlashlightProvider.class.getSimpleName();
private Camera mCamera;
private Camera.Parameters parameters;
private CameraManager camManager;
private Context context;

public FlashlightProvider(Context context) {
    this.context = context;
}

private void turnFlashlightOn() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            String cameraId = null; 
            if (camManager != null) {
                cameraId = camManager.getCameraIdList()[0];
                camManager.setTorchMode(cameraId, true);
            }
        } catch (CameraAccessException e) {
            Log.e(TAG, e.toString());
        }
    } else {
        mCamera = Camera.open();
        parameters = mCamera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        mCamera.setParameters(parameters);
        mCamera.startPreview();
    }
}

private void turnFlashlightOff() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            String cameraId;
            camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            if (camManager != null) {
                cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
                camManager.setTorchMode(cameraId, false);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    } else {
        mCamera = Camera.open();
        parameters = mCamera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        mCamera.setParameters(parameters);
        mCamera.stopPreview();
    }
}
}

其他回答

我得到了自动闪光与以下简单的三步。

我刚刚在Manifest.xml文件中添加了相机和Flash权限

< uses-permission android: name = " android.permission。相机" / > < uses-feature android: name = " android.hardware。相机" / > < uses-permission android: name = " android.permission.FLASHLIGHT " / > < uses-feature android: name = " android.hardware.camera。Flash " android:required="false" />

In your Camera Code do this way. //Open Camera Camera mCamera = Camera.open(); //Get Camera Params for customisation Camera.Parameters parameters = mCamera.getParameters(); //Check Whether device supports AutoFlash, If you YES then set AutoFlash List<String> flashModes = parameters.getSupportedFlashModes(); if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO)) { parameters.setFlashMode(Parameters.FLASH_MODE_AUTO); } mCamera.setParameters(parameters); mCamera.startPreview(); Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.

在Marshmallow和上面的例子中,CameraManager的“setTorchMode()”似乎是答案。这对我来说很管用:

 final CameraManager mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
 CameraManager.TorchCallback torchCallback = new CameraManager.TorchCallback() {
     @Override
     public void onTorchModeUnavailable(String cameraId) {
         super.onTorchModeUnavailable(cameraId);
     }

     @Override
     public void onTorchModeChanged(String cameraId, boolean enabled) {
         super.onTorchModeChanged(cameraId, enabled);
         boolean currentTorchState = enabled;
         try {
             mCameraManager.setTorchMode(cameraId, !currentTorchState);
         } catch (CameraAccessException e){}



     }
 };

 mCameraManager.registerTorchCallback(torchCallback, null);//fires onTorchModeChanged upon register
 mCameraManager.unregisterTorchCallback(torchCallback);

在不同的Android版本中有不同的访问Camera Flash的方法。在棒棒糖中很少有api停止工作,然后在棉花糖中又发生了变化。为了克服这个问题,我创建了一个简单的库,我已经在我的几个项目中使用了它,它给出了很好的结果。它仍然是不完整的,但是您可以尝试检查代码并找到缺失的部分。这是链接- NoobCameraFlash。

如果你只是想在你的代码中集成,你可以使用gradle。以下是使用说明(直接从自述文件中获取)-

步骤1。将JitPack存储库添加到构建文件中。将它添加到您的根版本中。Gradle在存储库的末尾:

allprojects {
        repositories {
            ...
            maven { url "https://jitpack.io" }
        }
}

步骤2。添加依赖项

dependencies {
        compile 'com.github.Abhi347:NoobCameraFlash:0.0.1'
  }

使用

初始化NoobCameraManager单例。

NoobCameraManager.getInstance().init(this);

您可以选择为调试日志设置日志级别。日志使用LumberJack库。默认为“LogLevel”。没有一个

NoobCameraManager.getInstance().init(this, LogLevel.Verbose);

之后,你只需要调用单例来打开或关闭相机闪光灯。

NoobCameraManager.getInstance().turnOnFlash();
NoobCameraManager.getInstance().turnOffFlash();

您必须注意访问Camera的运行时权限 在初始化NoobCameraManager之前。在0.1.2版本中 或者更早的时候,我们使用直接从 库,但由于对Activity对象的依赖,我们必须 删除它。

切换Flash也很容易

if(NoobCameraManager.getInstance().isFlashOn()){
    NoobCameraManager.getInstance().turnOffFlash();
}else{
    NoobCameraManager.getInstance().turnOnFlash();
}

API 23或以上版本(Android M, 6.0)

打开代码

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; 
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);   //Turn ON
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

关闭代码

camManager.setTorchMode(cameraId, false);

和权限

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

额外的编辑

人们仍然在为我的答案投票,所以我决定发布额外的代码 这是我当时对这个问题的解决方案:

public class FlashlightProvider {

private static final String TAG = FlashlightProvider.class.getSimpleName();
private Camera mCamera;
private Camera.Parameters parameters;
private CameraManager camManager;
private Context context;

public FlashlightProvider(Context context) {
    this.context = context;
}

private void turnFlashlightOn() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            String cameraId = null; 
            if (camManager != null) {
                cameraId = camManager.getCameraIdList()[0];
                camManager.setTorchMode(cameraId, true);
            }
        } catch (CameraAccessException e) {
            Log.e(TAG, e.toString());
        }
    } else {
        mCamera = Camera.open();
        parameters = mCamera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        mCamera.setParameters(parameters);
        mCamera.startPreview();
    }
}

private void turnFlashlightOff() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            String cameraId;
            camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            if (camManager != null) {
                cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
                camManager.setTorchMode(cameraId, false);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    } else {
        mCamera = Camera.open();
        parameters = mCamera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        mCamera.setParameters(parameters);
        mCamera.stopPreview();
    }
}
}

根据我的经验,如果你的应用程序设计为纵向和横向工作,你需要声明变量凸轮为静态。否则,onDestroy()在切换方向时被调用,它会破坏它,但不会释放Camera,因此不可能再次重新打开它。

package com.example.flashlight;

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

public static Camera cam = null;// has to be static, otherwise onDestroy() destroys it

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void flashLightOn(View view) {

    try {
        if (getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA_FLASH)) {
            cam = Camera.open();
            Parameters p = cam.getParameters();
            p.setFlashMode(Parameters.FLASH_MODE_TORCH);
            cam.setParameters(p);
            cam.startPreview();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Exception flashLightOn()",
                Toast.LENGTH_SHORT).show();
    }
}

public void flashLightOff(View view) {
    try {
        if (getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA_FLASH)) {
            cam.stopPreview();
            cam.release();
            cam = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Exception flashLightOff",
                Toast.LENGTH_SHORT).show();
    }
}
}

为了证明我必须画这条线

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

从http://developer.android.com/reference/android/hardware/Camera.html

上面建议的台词对我不起作用。