web-dev-qa-db-fra.com

Android 5, camera2 n'utilise que le flash

Je n'ai besoin d'utiliser que le flash avec l'API camera2 (Android 5, API de niveau 21), comme pour les applications de la torche . Mais tous les exemples que j'ai trouvés nécessitent l'affichage du flux de caméra dans une vue.

16
dchwalid
16
yydcdut

Il suffit d’utiliser la classe suivante pour activer/désactiver FlashLight sous Android L,

public class FlashLightUtilForL {
    private CameraCaptureSession mSession;
    private CaptureRequest.Builder mBuilder;
    private CameraDevice mCameraDevice;
    private CameraManager mCameraManager;

    public FlashLightUtilForL(Context context) {
        try {
            mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            //here to judge if flash is available
            CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics("0");
            boolean flashAvailable = cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            if (flashAvailable) {
                mCameraManager.openCamera("0", new MyCameraDeviceStateCallback(), null);
            } else {
                //todo: throw Exception
            }
            //mCameraManager.openCamera("0", new MyCameraDeviceStateCallback(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyCameraDeviceStateCallback extends CameraDevice.StateCallback {

        @Override
        public void onOpened(CameraDevice camera) {
            mCameraDevice = camera;
            //get builder
            try {
                mBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_MANUAL);
                //flash on, default is on
                mBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AF_MODE_AUTO);
                mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
                List<Surface> list = new ArrayList<Surface>();
                SurfaceTexture mSurfaceTexture = new SurfaceTexture(1);
                Size size = getSmallestSize(mCameraDevice.getId());
                mSurfaceTexture.setDefaultBufferSize(size.getWidth(), size.getHeight());
                Surface mSurface = new Surface(mSurfaceTexture);
                list.add(mSurface);
                mBuilder.addTarget(mSurface);
                camera.createCaptureSession(list, new MyCameraCaptureSessionStateCallback(), null);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDisconnected(CameraDevice camera) {

        }

        @Override
        public void onError(CameraDevice camera, int error) {

        }
    }

    private Size getSmallestSize(String cameraId) throws CameraAccessException {
        Size[] outputSizes = mCameraManager.getCameraCharacteristics(cameraId)
                .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
                .getOutputSizes(SurfaceTexture.class);
        if (outputSizes == null || outputSizes.length == 0) {
            throw new IllegalStateException(
                    "Camera " + cameraId + "doesn't support any outputSize.");
        }
        Size chosen = outputSizes[0];
        for (Size s : outputSizes) {
            if (chosen.getWidth() >= s.getWidth() && chosen.getHeight() >= s.getHeight()) {
                chosen = s;
            }
        }
        return chosen;
    }

    /**
     * session callback
     */
    class MyCameraCaptureSessionStateCallback extends CameraCaptureSession.StateCallback {

        @Override
        public void onConfigured(CameraCaptureSession session) {
            mSession = session;
            try {
                mSession.setRepeatingRequest(mBuilder.build(), null, null);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onConfigureFailed(CameraCaptureSession session) {

        }
    }

    public void turnOnFlashLight() {
        try {
            mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
            mSession.setRepeatingRequest(mBuilder.build(), null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void turnOffFlashLight() {
        try {
            mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);
            mSession.setRepeatingRequest(mBuilder.build(), null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void close() {
        if (mCameraDevice == null || mSession == null) {
            return;
        }
        mSession.close();
        mCameraDevice.close();
        mCameraDevice = null;
        mSession = null;
    }
}
15
Umang Kothari

voici la démo complète vérifier cela.

package com.camera2;

import Android.content.Context;
import Android.graphics.SurfaceTexture;
import Android.hardware.camera2.CameraAccessException;
import Android.hardware.camera2.CameraCaptureSession;
import Android.hardware.camera2.CameraCharacteristics;
import Android.hardware.camera2.CameraDevice;
import Android.hardware.camera2.CameraManager;
import Android.hardware.camera2.CameraMetadata;
import Android.hardware.camera2.CaptureRequest;
import Android.os.Bundle;
import Android.support.v7.app.AppCompatActivity;
import Android.util.Size;
import Android.view.Surface;
import Android.view.View;
import Android.widget.Button;

import Java.util.ArrayList;
import Java.util.List;

public class MainActivity extends AppCompatActivity
    {
        private CameraManager cameraManager;
        private CameraCharacteristics cameraCharacteristics;

        private CameraDevice mCameraDevice;
        private CameraCaptureSession mSession;

        private CaptureRequest.Builder mBuilder;

        private Button on;
        private Button off;


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

                on = (Button) findViewById(R.id.on);
                off = (Button) findViewById(R.id.off);

                initCamera();
            }

        public void click(View v)
            {
                switch (v.getId())
                    {
                    case R.id.on:
                        try
                            {
                                turnOnFlashLight(); 
                            }
                        catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        break;
                    case R.id.off:
                        turnOffFlashLight();
                        break;
                    }
            }

        private void initCamera()
            {
                cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                try
                    {
                        String[] id = cameraManager.getCameraIdList();
                        if (id != null && id.length > 0)
                            {
                                cameraCharacteristics = cameraManager.getCameraCharacteristics(id[0]);
                                boolean isFlash = cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                                if (isFlash)
                                    {
                                        cameraManager.openCamera(id[0], new MyCameraDeviceStateCallback(), null);               
                                    }
                            }
                    }
                catch (CameraAccessException e)
                    {
                        e.printStackTrace();
                    }
            }

        class MyCameraDeviceStateCallback extends CameraDevice.StateCallback
            {

                @Override
                public void onOpened(CameraDevice camera)
                    {
                        mCameraDevice = camera;
                        // get builder
                        try
                            {
                                mBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                                List<Surface> list = new ArrayList<Surface>();
                                SurfaceTexture mSurfaceTexture = new SurfaceTexture(1);
                                Size size = getSmallestSize(mCameraDevice.getId());
                                mSurfaceTexture.setDefaultBufferSize(size.getWidth(), size.getHeight());
                                Surface mSurface = new Surface(mSurfaceTexture);
                                list.add(mSurface);
                                mBuilder.addTarget(mSurface);
                                camera.createCaptureSession(list, new MyCameraCaptureSessionStateCallback(), null);
                            }
                        catch (CameraAccessException e)
                            {
                                e.printStackTrace();
                            }
                    }

                @Override
                public void onDisconnected(CameraDevice camera)
                    {

                    }

                @Override
                public void onError(CameraDevice camera, int error)
                    {

                    }
            }

        private Size getSmallestSize(String cameraId) throws CameraAccessException
            {
                Size[] outputSizes = cameraManager.getCameraCharacteristics(cameraId).get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(SurfaceTexture.class);
                if (outputSizes == null || outputSizes.length == 0)
                    {
                        throw new IllegalStateException("Camera " + cameraId + "doesn't support any outputSize.");
                    }
                Size chosen = outputSizes[0];
                for (Size s : outputSizes)
                    {
                        if (chosen.getWidth() >= s.getWidth() && chosen.getHeight() >= s.getHeight())
                            {
                                chosen = s;
                            }
                    }
                return chosen;
            }

        class MyCameraCaptureSessionStateCallback extends CameraCaptureSession.StateCallback
            {
                @Override
                public void onConfigured(CameraCaptureSession session)
                    {
                        mSession = session;
                        try
                            {
                                mSession.setRepeatingRequest(mBuilder.build(), null, null);
                            }
                        catch (CameraAccessException e)
                            {
                                e.printStackTrace();
                            }
                    }

                @Override
                public void onConfigureFailed(CameraCaptureSession session)
                    {

                    }
            }

        public void turnOnFlashLight()
            {
                try
                    {
                        mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
                        mSession.setRepeatingRequest(mBuilder.build(), null, null);
                    }
                catch (Exception e)
                    {
                        e.printStackTrace();
                    }
            }

        public void turnOffFlashLight()
            {
                try
                    {
                        mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);
                        mSession.setRepeatingRequest(mBuilder.build(), null, null);
                    }
                catch (Exception e)
                    {
                        e.printStackTrace();
                    }
            }

        private void close()
            {
                if (mCameraDevice == null || mSession == null)
                    {
                        return;
                    }
                mSession.close();
                mCameraDevice.close();
                mCameraDevice = null;
                mSession = null;
            }
    }

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.camera2.MainActivity">

    <Button
        Android:onClick="click"
        Android:id="@+id/on"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="On" />

    <Button
        Android:onClick="click"
        Android:id="@+id/off"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="Off" />
</LinearLayout>

manifeste

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:Android="http://schemas.Android.com/apk/res/Android"
    package="com.camera2">


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

    <uses-feature Android:name="Android.hardware.camera" />
    <uses-feature Android:name="Android.hardware.camera.autofocus" />
    <uses-feature Android:name="Android.hardware.camera.flash" />

    <application
        Android:allowBackup="true"
        Android:icon="@mipmap/ic_launcher"
        Android:label="@string/app_name"
        Android:supportsRtl="true"
        Android:theme="@style/AppTheme">
        <activity Android:name=".MainActivity">
            <intent-filter>
                <action Android:name="Android.intent.action.MAIN" />

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

</manifest>

utilisez close () pour fermer les paramètres de l'appareil photo

3
rizwan

Eh bien, cela a parfaitement fonctionné pour moi:

public class MainActivity extends AppCompatActivity {
    ToggleButton button;
    boolean flashLightStatus = true;
    boolean deviceHasCameraFlash = getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (ToggleButton) findViewById(R.id.button);
        FlashLightOn();//When app opens, turn it on.
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(deviceHasCameraFlash){
                    if(flashLightStatus){//when light on
                        FlashLightOff();//we should off
                    }
                    else //when light off
                        FlashLightOn();//we should on
                }
                else
                    Toast.makeText(MainActivity.this, "No flash available on your device.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void FlashLightOn() {
        CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try{
            String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
            camManager.setTorchMode(cameraId, true);
            flashLightStatus=true;
        } catch (Exception e){

        }
    }
    private void FlashLightOff() {
        CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try{

            String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
            camManager.setTorchMode(cameraId, false);
            flashLightStatus=false;
        } catch (Exception e){

        }
    }
}
0
user5229412