如何安全退出Android Camera2BasicFragment并在下一个活动中显示捕获的图像? [重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

这可能是一个愚蠢的问题,但我面临着安全退出Camera2BasicFragment的问题。

我使用了Google的示例代码来实现Camera2 API。 Google Camera2 Sample code

请建议我必须将Intent准确放在下一个活动中,我想要显示捕获的图像并安全退出相机活动。

当我尝试导航到下一个活动时,相机会冻结。我试着关闭相机,停止后台线程。但是我做得不对,因为屏幕冻结了。

我想在这里实现它。如果我必须在其他地方这样做,请告诉我。我已经使用了示例代码,如果您需要引用代码,请使用上面提到的链接。

Camera2BasicFragment ImageSaver功能:

private class ImageSaver implements Runnable {

        /**
         * The JPEG image
         */
        private final Image mImage;
        /**
         * The file we save the image into.
         */
        private final File mFile;

        ImageSaver(Image image, File file) {
            mImage = image;
            mFile = file;
        }

        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            Bitmap capturedImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

            int width = linearLayout.getWidth();
            int height = linearLayout.getHeight();

            int left = width/6;
            int top = height/8;
            Log.e("LEFT TOP", left + " " +top);

            croppedImage = Bitmap.createBitmap(capturedImage, left, top, 5*(width/6), 2*(height/3));

            /**
             * 
             * This is the region of trouble
             * I'm cropping the image and trying to display it in the next activity
             *
             */
            onPause();
            startActivity(new Intent(getActivity(), DisplayImage.class).putExtra("BITMAP", croppedImage));
        }

    }

当我在ImageSaver()执行后尝试启动下一个活动时,堆栈跟踪

A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0xdb321004 in tid 21857 (CameraBackgroun)
Application terminated.
android multithreading android-intent android-camera2
2个回答
0
投票

尝试在主线程上启动活动。

  Handler handler = new Handler(Looper.getMainLooper());
  handler.post(new Runnable() {
  @Override
  public void run() {

      startActivity(intent);
  }
 });

不应该打电话给onPause。


0
投票

您无法通过Intent将位图作为可分配的额外内容传递:它太大了。没有必要save the bitmap as file

简单的方法是使用Application对象(在Android上基本上是一个单例)来保存这些数据,但是有其他模式:with a static field in the first Activitypass it as a compressed byteArray

© www.soinside.com 2019 - 2024. All rights reserved.