尝试使用Android Camera2创建手电筒

独奏

我正在尝试使用Camera2创建手电筒。我遇到了错误。当我尝试打开或关闭手电筒时,出现错误消息:

android.hardware.camera2.CameraAccessExeption:摄像头设备遇到严重错误。

主要活动

package com.nettport.lommelykt;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
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.util.Size;
import android.view.Surface;
import java.util.ArrayList;
import java.util.List;


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

    CameraDevice mCameraDevice;
    CameraCaptureSession mSession;

    CaptureRequest.Builder mBuilder;


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

        // Initialize camera
        initCamera();

        // Click button on or off
        ToggleButton onOffButton = (ToggleButton) findViewById(R.id.toggleButton);
        onOffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // your click actions go here
                if (((ToggleButton) v).isChecked()) {
                    changeTextAndIcon(1);
                    turnOnFlashLight();
                } else {
                    changeTextAndIcon(0);
                    turnOffFlashLight();
                }
            }
        });

    }

    /*- Change text and icon ------------------------------------- */
    // modus = 1 -> turn on
    // modus = 0 -> turn off
    void changeTextAndIcon(int modus) {
        // Change text
        TextView statusText = (TextView) findViewById(R.id.textView);
        if (modus == 1) {
            statusText.setText("Lommelykten er på"); // Flash  is on
        } else {
            statusText.setText("Lommelykten er av"); // Flash is off
        }

        // Change icon to off
        ImageView flashlightIcon = (ImageView) findViewById(R.id.imageView);
        if (modus == 1) {
            flashlightIcon.setImageResource(R.drawable.flashlight_on);
        } else {
            flashlightIcon.setImageResource(R.drawable.flashlight_off);
        }
    }

    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) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    cameraManager.openCamera(id[0], new MyCameraDeviceStateCallback(), null);
                    Toast.makeText(this, "Camera initialized", Toast.LENGTH_LONG).show();
                }
            }
        }
        catch (CameraAccessException e)
        {
            e.printStackTrace();
            Toast.makeText(this, "Camera initialization error:\n" + e.toString(), Toast.LENGTH_LONG).show();
        }
    }

    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);
            Toast.makeText(this, "Flash activated", Toast.LENGTH_LONG).show();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(this, "Flash failed:\n" + e.toString(), Toast.LENGTH_LONG).show();
        }
    }

    public void turnOffFlashLight()
    {
        try
        {
            mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);
            mSession.setRepeatingRequest(mBuilder.build(), null, null);
            Toast.makeText(this, "Flash disabled", Toast.LENGTH_LONG).show();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(this, "Flash failed:\n" + e.toString(), Toast.LENGTH_LONG).show();
        }
    }

    private void close()
    {
        Toast.makeText(this, "Camera closed", Toast.LENGTH_LONG).show();
        if (mCameraDevice == null || mSession == null)
        {
            return;
        }
        mSession.close();
        mCameraDevice.close();
        mCameraDevice = null;
        mSession = null;
    }

}

Android清单

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

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


    <!-- Allows access to the flashlight -->

    <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" />


</manifest>
埃迪·塔尔瓦拉

您没有坚持使用SurfaceTexture。由此创建的Surface大致等于一个弱指针,并且不会阻止SurfaceTexture被垃圾回收。

查看将SurfaceTexture存储在MainActivity中是否可以解决您的问题。如果不是,您将需要提供崩溃的日志(不仅仅是应用程序日志记录,整个系统),以更详细地了解相机服务所抱怨的问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

android延迟手电筒

来自分类Dev

火炬/手电筒应用程序(不建议使用android.hardware.camera)

来自分类Dev

火炬/手电筒应用程序(不建议使用android.hardware.camera)

来自分类Dev

使用相机api 2的Android手电筒应用程序

来自分类Dev

Android片段中的手电筒-SurfaceView

来自分类Dev

在Android中以不同的模式打开手电筒

来自分类Dev

android手电筒崩溃在银河系联系

来自分类Dev

火炬/手电筒无法在Android应用中打开

来自分类Dev

在Android中以不同的模式打开手电筒

来自分类Dev

Nexus 5上的Android手电筒

来自分类Dev

Android片段中的手电筒-SurfaceView

来自分类Dev

在Android上打开/关闭相机手电筒

来自分类Dev

Android Studio:手电筒在关闭时崩溃

来自分类Dev

使用SurfaceView打开/关闭手电筒

来自分类Dev

使用kivy / python访问android手电筒(相机LED闪光灯)

来自分类Dev

使用kivy / python访问android手电筒(相机LED闪光灯)

来自分类Dev

尝试安装手电筒时出现“E:包‘ipython’没有安装候选”

来自分类Dev

Android手电筒应用程序每隔一次启动就会崩溃

来自分类Dev

在Android模拟器中模拟LED手电筒?

来自分类Dev

android手电筒第二次启动错误

来自分类Dev

如何在Android N中打开设备手电筒?

来自分类Dev

在Android中打开不支持同时闪光的手电筒和相机

来自分类Dev

在所有 Android 设备中控制手电筒

来自分类Dev

使用新的Firebase在Heroku上为ElasticSearch设置手电筒

来自分类Dev

使用新的Firebase在Heroku上为ElasticSearch设置手电筒

来自分类Dev

iOS 10.2-使用手电筒激活Retina Flash而不是Back LED

来自分类Dev

如何仅在Unity3d中使用C#打开/关闭Android手电筒

来自分类Dev

如何仅在Unity3d中使用C#打开/关闭android手电筒

来自分类Dev

2D恐怖游戏手电筒

Related 相关文章

  1. 1

    android延迟手电筒

  2. 2

    火炬/手电筒应用程序(不建议使用android.hardware.camera)

  3. 3

    火炬/手电筒应用程序(不建议使用android.hardware.camera)

  4. 4

    使用相机api 2的Android手电筒应用程序

  5. 5

    Android片段中的手电筒-SurfaceView

  6. 6

    在Android中以不同的模式打开手电筒

  7. 7

    android手电筒崩溃在银河系联系

  8. 8

    火炬/手电筒无法在Android应用中打开

  9. 9

    在Android中以不同的模式打开手电筒

  10. 10

    Nexus 5上的Android手电筒

  11. 11

    Android片段中的手电筒-SurfaceView

  12. 12

    在Android上打开/关闭相机手电筒

  13. 13

    Android Studio:手电筒在关闭时崩溃

  14. 14

    使用SurfaceView打开/关闭手电筒

  15. 15

    使用kivy / python访问android手电筒(相机LED闪光灯)

  16. 16

    使用kivy / python访问android手电筒(相机LED闪光灯)

  17. 17

    尝试安装手电筒时出现“E:包‘ipython’没有安装候选”

  18. 18

    Android手电筒应用程序每隔一次启动就会崩溃

  19. 19

    在Android模拟器中模拟LED手电筒?

  20. 20

    android手电筒第二次启动错误

  21. 21

    如何在Android N中打开设备手电筒?

  22. 22

    在Android中打开不支持同时闪光的手电筒和相机

  23. 23

    在所有 Android 设备中控制手电筒

  24. 24

    使用新的Firebase在Heroku上为ElasticSearch设置手电筒

  25. 25

    使用新的Firebase在Heroku上为ElasticSearch设置手电筒

  26. 26

    iOS 10.2-使用手电筒激活Retina Flash而不是Back LED

  27. 27

    如何仅在Unity3d中使用C#打开/关闭Android手电筒

  28. 28

    如何仅在Unity3d中使用C#打开/关闭android手电筒

  29. 29

    2D恐怖游戏手电筒

热门标签

归档