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

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


当前回答

试试这个。

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; // Usually front camera is at 0 position.
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

其他回答

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

我刚刚在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.

2022年Kotlin版本:

fun Context.isFlashLightAvailable() = packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)

val Context.camaraManager: CameraManager get() = getSystemService(CameraManager::class.java)


fun Context.toggleFlashLight(on: Boolean) {
    camaraManager.run {

        val firstCameraWithFlash = cameraIdList.find { camera ->
            getCameraCharacteristics(camera).keys.any { it == FLASH_INFO_AVAILABLE }
        }

        firstCameraWithFlash?.let {
            runCatching { setTorchMode(it, on) }.onFailure { Timber.e(it, "Error setTorchMode") }
        } ?: Timber.e(Throwable("toggleFlashLight"), "Camera with flash not found")

    }
}

或者用一个返回结果的挂起函数

suspend fun Context.toggleFlashLightWithResult(on: Boolean): Boolean {
    return suspendCancellableCoroutine { cont ->
        runCatching {
            camaraManager.run {

                val firstCameraWithFlash = cameraIdList.find { camera ->
                    getCameraCharacteristics(camera).keys.any { it == FLASH_INFO_AVAILABLE }
                }

                val callback = object : CameraManager.TorchCallback() {
                    override fun onTorchModeChanged(cameraId: String, enabled: Boolean) {
                        super.onTorchModeChanged(cameraId, enabled)
            
                       if (cont.isActive) cont.resume(enabled)
                    }
                }

                if (firstCameraWithFlash == null) {
                    Timber.e(Throwable("toggleFlashLight"), "Camera with flash not found")
                    cont.resume(false)
                } else {
                    Timber.tag("~!").d("firstCameraWithFlash: $firstCameraWithFlash")
                    setTorchMode(firstCameraWithFlash, on)
                    registerTorchCallback(mainExecutor, callback)
                }

                cont.invokeOnCancellation { unregisterTorchCallback(callback) }
            }
        }
            .onFailure { Timber.e(it, "Error toggleFlashLight") }

    }
}

完整的代码为android手电筒应用程序

清单

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.user.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="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
              android:name=".MainActivity"
              android:label="@string/app_name" >
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />

                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>

  </manifest>

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OFF"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="turnFlashOnOrOff" />
</RelativeLayout>

MainActivity.java

  import android.app.AlertDialog;
  import android.content.DialogInterface;
  import android.content.pm.PackageManager;
  import android.hardware.Camera;
  import android.hardware.Camera.Parameters;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;

  import java.security.Policy;

  public class MainActivity extends AppCompatActivity {

      Button button;
      private Camera camera;
      private boolean isFlashOn;
      private boolean hasFlash;
      Parameters params;

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

          button = (Button) findViewById(R.id.button);

          hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

          if(!hasFlash) {

              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() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      finish();
                  }
              });
              alert.show();
              return;
          }

          getCamera();

          button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {

                  if (isFlashOn) {
                      turnOffFlash();
                      button.setText("ON");
                  } else {
                      turnOnFlash();
                      button.setText("OFF");
                  }

              }
          });
      }

      private void getCamera() {

          if (camera == null) {
              try {
                  camera = Camera.open();
                  params = camera.getParameters();
              }catch (Exception e) {

              }
          }

      }

      private void turnOnFlash() {

          if(!isFlashOn) {
              if(camera == null || params == null) {
                  return;
              }

              params = camera.getParameters();
              params.setFlashMode(Parameters.FLASH_MODE_TORCH);
              camera.setParameters(params);
              camera.startPreview();
              isFlashOn = true;
          }

      }

      private void turnOffFlash() {

              if (isFlashOn) {
                  if (camera == null || params == null) {
                      return;
                  }

                  params = camera.getParameters();
                  params.setFlashMode(Parameters.FLASH_MODE_OFF);
                  camera.setParameters(params);
                  camera.stopPreview();
                  isFlashOn = false;
              }
      }

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

  }

你也可以使用下面的代码来关闭闪光灯。

Camera.Parameters params = mCamera.getParameters()
p.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);

根据我的经验,如果你的应用程序设计为纵向和横向工作,你需要声明变量凸轮为静态。否则,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

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