0

раньше все работало, но сейчас фото перестали сохранятся, с чем связана эта ошибка? Может надо добавить какие-нибудь исключения.

Код камеры:

import android.Manifest;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
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.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class fragment7 extends Fragment {

    private Button btnCapture;
    private TextureView textureView;
    private Context mContext;

    //Check state orientation of output image
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static{
        ORIENTATIONS.append(Surface.ROTATION_0,90);
        ORIENTATIONS.append(Surface.ROTATION_90,0);
        ORIENTATIONS.append(Surface.ROTATION_180,270);
        ORIENTATIONS.append(Surface.ROTATION_270,180);
    }

    private String cameraId;
    private CameraDevice cameraDevice;
    private CameraCaptureSession cameraCaptureSessions;
    private CaptureRequest.Builder captureRequestBuilder;
    private Size imageDimension;
    private ImageReader imageReader;

    //Save to FILE
    private File file;
    private static final int REQUEST_CAMERA_PERMISSION = 200;
    private boolean mFlashSupported;
    private Handler mBackgroundHandler;
    private HandlerThread mBackgroundThread;

    CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice camera) {
            cameraDevice = camera;
            createCameraPreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            cameraDevice.close();
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int i) {
            cameraDevice.close();
            cameraDevice=null;
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment7, container, false);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles

        mContext = getActivity().getApplicationContext();
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments

        textureView = (TextureView)view.findViewById(R.id.textureView);
        //From Java 1.4 , you can use keyword 'assert' to check expression true or false
        assert textureView != null;
        textureView.setSurfaceTextureListener(textureListener);

        DisplayMetrics metrics = this.getResources().getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;

        btnCapture = (Button)view.findViewById(R.id.btnCapture);
        btnCapture.setX(width/2-64);
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePicture();
            }
        });
        File file = new File(getActivity().getExternalCacheDir()+"/saved.jpg");
        Log.d("dsdsds", "123");
        if (file.exists()) {

            if (globalvariables.image_count == 3){
                globalvariables.image_count = 0;
            }

            globalvariables.bitmap_for_report[globalvariables.image_count] = BitmapFactory.decodeFile(file.getAbsolutePath());

            String info =
                    String.format("Info: size = %s x %s, bytes = %s (%s), config = %s",
                            globalvariables.bitmap_for_report[globalvariables.image_count].getWidth(),
                            globalvariables.bitmap_for_report[globalvariables.image_count].getHeight(),
                            globalvariables.bitmap_for_report[globalvariables.image_count].getByteCount(),
                            globalvariables.bitmap_for_report[globalvariables.image_count].getRowBytes(),
                            globalvariables.bitmap_for_report[globalvariables.image_count].getConfig());
            Log.d("log", info);
            ++globalvariables.image_count;

        }
        getActivity().setTitle("Фото");
    }


    private void takePicture() {
        if(cameraDevice == null)
            return;
        CameraManager manager = (CameraManager) getActivity().getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
        try{
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
            Size[] jpegSizes = null;
            if(characteristics != null)
                jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
                        .getOutputSizes(ImageFormat.JPEG);

            //Capture image with custom size
            int width = 640;
            int height = 480;
            if(jpegSizes != null && jpegSizes.length > 0)
            {
                width = jpegSizes[0].getWidth();
                height = jpegSizes[0].getHeight();
            }
            final ImageReader reader = ImageReader.newInstance(width,height,ImageFormat.JPEG,1);
            List<Surface> outputSurface = new ArrayList<>(2);
            outputSurface.add(reader.getSurface());
            outputSurface.add(new Surface(textureView.getSurfaceTexture()));

            final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(reader.getSurface());
            captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);

            //Check orientation base on device
            int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));
            if (globalvariables.nimg == 0) {
                file = new File(getActivity().getExternalCacheDir() + "/saved"+String.valueOf(globalvariables.nimg)+".jpg");
                globalvariables.nimg = 1;
            }
            else{
                if (globalvariables.nimg ==1) {
                    file = new File(getActivity().getExternalCacheDir() + "/saved"+String.valueOf(globalvariables.nimg)+".jpg");
                    globalvariables.nimg = 2;
                }
                else{
                    if (globalvariables.nimg == 2) {
                        file = new File(getActivity().getExternalCacheDir() + "/saved"+String.valueOf(globalvariables.nimg)+".jpg");
                        globalvariables.nimg = 0;
                    }
                }
            }
            ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
                @Override
                public void onImageAvailable(ImageReader imageReader) {
                    Image image = null;
                    try{
                        image = reader.acquireLatestImage();
                        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                        byte[] bytes = new byte[buffer.capacity()];
                        buffer.get(bytes);
                        save(bytes);

                    }
                    catch (FileNotFoundException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    finally {
                        {
                            if(image != null)
                                image.close();
                        }
                    }
                }
                private void save(byte[] bytes) throws IOException {
                    OutputStream outputStream = null;
                    try{
                        outputStream = new FileOutputStream(file);
                        outputStream.write(bytes);
                    }finally {
                        if(outputStream != null)
                            outputStream.close();
                    }
                }
            };

            reader.setOnImageAvailableListener(readerListener,mBackgroundHandler);
            final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                    super.onCaptureCompleted(session, request, result);
                    Toast.makeText(getActivity().getApplicationContext(), "Saved "+file, Toast.LENGTH_SHORT).show();
                    createCameraPreview();

                    fragment6 frag6 = new fragment6();
                    FragmentTransaction fTrans = getFragmentManager().beginTransaction();
                    fTrans.replace(R.id.frgmCont, frag6);
                    fTrans.commit();
                }
            };

            cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    try{
                        cameraCaptureSession.capture(captureBuilder.build(),captureListener,mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {

                }
            },mBackgroundHandler);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

    }

    private void createCameraPreview() {
        try{
            SurfaceTexture texture = textureView.getSurfaceTexture();
            assert  texture != null;
            texture.setDefaultBufferSize(imageDimension.getWidth(),imageDimension.getHeight());
            Surface surface = new Surface(texture);
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(surface);
            cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    if(cameraDevice == null)
                        return;
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(getActivity().getApplicationContext(), "Changed", Toast.LENGTH_SHORT).show();
                }
            },null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void updatePreview() {
        if(cameraDevice == null)
            Toast.makeText(getActivity().getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
        captureRequestBuilder.set(CaptureRequest.CONTROL_MODE,CaptureRequest.CONTROL_MODE_AUTO);
        try{
            cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),null,mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    private void openCamera() {
        CameraManager manager = (CameraManager) getActivity().getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
        try{
            cameraId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;
            imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
            //Check realtime permission if run higher API 23
            if(ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
            {
                ActivityCompat.requestPermissions(getActivity(),new String[]{
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                },REQUEST_CAMERA_PERMISSION);
                return;
            }
            manager.openCamera(cameraId,stateCallback,null);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
            openCamera();
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == REQUEST_CAMERA_PERMISSION)
        {
            if(grantResults[0] != PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(getActivity().getApplicationContext(), "You can't use camera without permission", Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        startBackgroundThread();
        if(textureView.isAvailable())
            openCamera();
        else
            textureView.setSurfaceTextureListener(textureListener);
    }

    @Override
    public void onPause() {
        stopBackgroundThread();
        super.onPause();
    }

    private void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try{
            mBackgroundThread.join();
            mBackgroundThread= null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("Camera Background");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
}

08-24 06:31:59.153 5380-5380/com.example.jone1.navigation_drawer I/RequestQueue: Repeating capture request cancelled. 08-24 06:31:59.181 5380-9692/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state IDLE 08-24 06:31:59.185 5380-5380/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state CONFIGURING 08-24 06:31:59.186 5380-9692/com.example.jone1.navigation_drawer I/RequestThread-0: Configure outputs: 2 surfaces configured. 08-24 06:31:59.231 5380-9692/com.example.jone1.navigation_drawer D/Camera: app passed NULL surface 08-24 06:31:59.244 5380-9692/com.example.jone1.navigation_drawer I/RequestThread-0: configureOutputs - set take picture size to 4160x3120 08-24 06:31:59.272 5380-5380/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state IDLE 08-24 06:31:59.284 5380-9692/com.example.jone1.navigation_drawer W/LegacyRequestMapper: convertRequestMetadata - control.awbRegions setting is not supported, ignoring value 08-24 06:31:59.284 5380-9692/com.example.jone1.navigation_drawer W/LegacyRequestMapper: Only received metering rectangles with weight 0. 08-24 06:31:59.284 5380-9692/com.example.jone1.navigation_drawer W/LegacyRequestMapper: Only received metering rectangles with weight 0. 08-24 06:31:59.372 5380-5392/com.example.jone1.navigation_drawer I/art: Background partial concurrent mark sweep GC freed 306816(12MB) AllocSpace objects, 7(188KB) LOS objects, 25% free, 47MB/63MB, paused 1.108ms total 226.305ms 08-24 06:31:59.681 5380-9619/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state CAPTURING 08-24 06:31:59.948 5380-9619/com.example.jone1.navigation_drawer I/RequestThread-0: Received jpeg. 08-24 06:31:59.948 5380-9619/com.example.jone1.navigation_drawer I/RequestThread-0: Producing jpeg buffer... 08-24 06:31:59.957 5380-9618/com.example.jone1.navigation_drawer W/ImageReader_JNI: Unable to acquire a buffer item, very likely client tried to acquire more than maxImages buffers 08-24 06:31:59.981 5380-9692/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state IDLE 08-24 06:31:59.994 5380-9618/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state CONFIGURING 08-24 06:31:59.995 5380-9692/com.example.jone1.navigation_drawer I/RequestThread-0: Configure outputs: 1 surfaces configured. 08-24 06:31:59.995 5380-9692/com.example.jone1.navigation_drawer D/Camera: app passed NULL surface 08-24 06:32:00.050 5380-9618/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state IDLE 08-24 06:32:00.056 5380-9618/com.example.jone1.navigation_drawer W/MessageQueue: Handler (android.view.ViewRootImpl$ViewRootHandler) {ea793cb} sending message to a Handler on a dead thread java.lang.IllegalStateException: Handler (android.view.ViewRootImpl$ViewRootHandler) {ea793cb} sending message to a Handler on a dead thread at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543) at android.os.Handler.enqueueMessage(Handler.java:646) at android.os.Handler.sendMessageAtTime(Handler.java:612) at android.view.ViewRootImpl$ViewRootHandler.sendMessageAtTime(ViewRootImpl.java:3493) at android.os.Handler.sendMessageDelayed(Handler.java:582) at android.os.Handler.post(Handler.java:338) at android.view.ViewRootImpl.loadSystemProperties(ViewRootImpl.java:6012) at android.view.ViewRootImpl.(ViewRootImpl.java:457) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:337) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94) at android.widget.Toast$TN.handleShow(Toast.java:463) at android.widget.Toast$TN$2.handleMessage(Toast.java:346) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:163) at android.os.HandlerThread.run(HandlerThread.java:61) 08-24 06:32:00.061 5380-9618/com.example.jone1.navigation_drawer I/Toast: Show toast from OpPackageName:com.example.jone1.navigation_drawer, PackageName:com.example.jone1.navigation_drawer 08-24 06:32:00.062 5380-9618/com.example.jone1.navigation_drawer I/RequestQueue: Repeating capture request set. 08-24 06:32:00.063 5380-5380/com.example.jone1.navigation_drawer E/TEST: Parent height = 1080, Parent width = 720 08-24 06:32:00.068 5380-9692/com.example.jone1.navigation_drawer W/LegacyRequestMapper: convertRequestMetadata - control.awbRegions setting is not supported, ignoring value 08-24 06:32:00.068 5380-9692/com.example.jone1.navigation_drawer W/LegacyRequestMapper: Only received metering rectangles with weight 0. 08-24 06:32:00.068 5380-9692/com.example.jone1.navigation_drawer W/LegacyRequestMapper: Only received metering rectangles with weight 0. 08-24 06:32:00.146 5380-5380/com.example.jone1.navigation_drawer E/TEST: Parent height = 0, Parent width = 0 08-24 06:32:00.287 5380-9695/com.example.jone1.navigation_drawer I/CameraDeviceState: Legacy camera service transitioning to state CAPTURING

2

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.