Xamarin - 相机类或对象阻止我的手机相机工作

时间:2017-11-30 05:17:45

标签: xamarin

我写了一个开启手电筒的应用程序。我唯一的问题是,每次打开我的应用程序时,我的手机摄像头选项都会停止工作 - 这就是我不能再打开相机了。只有在我杀死我的应用程序时相机才会开始工作。这是我的代码:

public static Camera camera = null;

我在ON按钮中调用TurnCameraOn(),在OFF按钮中调用TurnCameraOff。

private void TurnCameraOn()
        {
            if (CameraAvailable() == true)
            {
                if (camera == null)
                    camera = Camera.Open();

                Camera.Parameters parameters = camera.GetParameters();
                parameters.FlashMode = Camera.Parameters.FlashModeTorch;

                camera.SetParameters(parameters);
                Android.Graphics.SurfaceTexture mPreviewTexture = new Android.Graphics.SurfaceTexture(0);

                camera.SetPreviewTexture(mPreviewTexture);
                camera.StartPreview();

                cameraFlashLightOnThread = true;
            }
        }

        private void TurnCameraOff()
        {
            if (CameraAvailable() == true)
            {
                if (camera == null)
                    camera = Camera.Open();

                Camera.Parameters parameters = camera.GetParameters();

                parameters.FlashMode = Camera.Parameters.FlashModeOff;

                camera.SetParameters(parameters);
                camera.StopPreview();

                cameraFlashLightOnThread = false;
            }
        }

        private bool CameraAvailable()
        {
            bool availale = true;

            if (PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureCamera) == false)
            {
                availale = false;
                Toast.MakeText(this, "No back-facing camera available", ToastLength.Long);
            }

            if (PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureCameraFlash) == false)
            {
                availale = false;

                Toast.MakeText(this, "No camera flash available", ToastLength.Long);
            }

            return availale;
        }

1 个答案:

答案 0 :(得分:1)

您的应用程序持有对相机的引用并且从不释放它。关闭LED /闪光灯时,请丢弃相机实例,以便其他应用程序可以使用相机。

类似的东西:

JLabel

仅供参考:您的private void TurnCameraOn() { if (CameraAvailable()) { camera = camera ?? Camera.Open(); using (var parameters = camera.GetParameters()) { parameters.FlashMode = Camera.Parameters.FlashModeTorch; camera.SetParameters(parameters); Android.Graphics.SurfaceTexture mPreviewTexture = new Android.Graphics.SurfaceTexture(0); camera.SetPreviewTexture(mPreviewTexture); camera.StartPreview(); } cameraFlashLightOnThread = true; } } private void TurnCameraOff() { if (CameraAvailable()) { camera = camera ?? Camera.Open(); using (var parameters = camera.GetParameters()) { parameters.FlashMode = Camera.Parameters.FlashModeOff; camera.SetParameters(parameters); camera.StopPreview(); camera.Dispose(); camera = null; } cameraFlashLightOnThread = false; } } 语句缺失Toast,因此永远不会向用户显示。