How to turn on front flash light programmatically in Android?

后端 未结 11 1592
执笔经年
执笔经年 2020-11-22 00:17

I want to turn on front flash light (not with camera preview) programmatically in Android. I googled for it but the help i found referred me to this page

Does anyo

相关标签:
11条回答
  • 2020-11-22 01:00

    Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.

    It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!

    To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.


    Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.

    0 讨论(0)
  • 2020-11-22 01:02

    From my experience, if your application is designed to work in both portrait and landscape orientation, you need to declare the variable cam as static. Otherwise, onDestroy(), which is called on switching orientation, destroys it but doesn't release Camera so it's not possible to reopen it again.

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

    to manifest I had to put this line

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

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

    suggested lines above wasn't working for me.

    0 讨论(0)
  • 2020-11-22 01:02

    In Marshmallow and above, CameraManager's `setTorchMode()' seems to be the answer. This works for me:

     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);
    
    0 讨论(0)
  • 2020-11-22 01:02

    You can also use the following code to turn off the flash.

    Camera.Parameters params = mCamera.getParameters()
    p.setFlashMode(Parameters.FLASH_MODE_OFF);
    mCamera.setParameters(params);
    
    0 讨论(0)
  • 2020-11-22 01:10

    In API 23 or Higher (Android M, 6.0)

    Turn On code

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

    Turn OFF code

    camManager.setTorchMode(cameraId, false);
    

    And Permissions

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

    ADDITIONAL EDIT

    People still upvoting my answer so I decided to post additional code This was my solution for the problem back in the day:

    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();
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题