pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

Android camera , onPictureTaken(byte[] imgData, Camera camera

Android camera , onPictureTaken(byte[] imgData, Camera camera) method amp; PictureCallback never called(Android camera , onPictureTaken(byte[] imgData, Camera camera) 方法 amp;PictureCallback 從未調(diào)用過) - IT屋-程序員軟件開發(fā)技
本文介紹了Android camera , onPictureTaken(byte[] imgData, Camera camera) 方法 &PictureCallback 從未調(diào)用過的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

我有一個(gè)自定義相機(jī)應(yīng)用程序,它可以在 SurfaceView 上預(yù)覽相機(jī)視頻輸出并嘗試拍照,這些照片應(yīng)該由xzing"掃描儀 API 處理,以解碼圖像中的任何條形碼.

I have a custom camera app , that previews the camera video output on SurfaceView and attempts to take pictures , the pics should be will be processed by "xzing "scanner API to decode any barcodes in the image.

我的應(yīng)用可以正確預(yù)覽并且不會拋出任何錯(cuò)誤或期望,但是我的 onPictureTaken(byte[] imgData, Camera camera) 方法和PictureCallback 永遠(yuǎn)不會被調(diào)用,因此我無法獲取圖像 &繼續(xù)進(jìn)一步掃描.

My app previews correctly and does not throw any errors or expectations, however my onPictureTaken(byte[] imgData, Camera camera) method & PictureCallback are never called, therefore I’m unable to get the image & continue with further scanning.

以下是負(fù)責(zé)相機(jī)邏輯的活動的實(shí)際代碼.onPictureTaken(byte[] imgData, Camera camera) 方法 &PictureCallback 都在這個(gè)類中(ScanVinFromBarcodeActivity.java)見吹:

package com.ty.tyownerspoc.barcode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource; 
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ty.tyownerspoc.R;

public class ScanVinFromBarcodeActivity extends Activity {

    private Camera globalCamera;
    private int cameraId = 0;
    private TextView VINtext = null;
    private View scanButton = null;
    // bitmap from camera
    private Bitmap bmpOfTheImageFromCamera = null;
    // global flag whether a camera has been detected
    private boolean isThereACamera = false;
    // surfaceView for preview object
    private FrameLayout frameLayoutBarcodeScanner = null;
    private CameraPreview newCameraPreview = null;
    private SurfaceView surfaceViewBarcodeScanner = null;
    private int counter = 0; 
    private volatile boolean finishedPictureTask  = false;
    /*
     * This method , finds FEATURE_CAMERA, opens the camera, set parameters ,
     * add CameraPreview to layout, set camera surface holder, start preview
     */
    private void initializeGlobalCamera() {
        try {
            if (!getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_CAMERA)) {
                Toast.makeText(this, "No camera on this device",
                        Toast.LENGTH_LONG).show();
            } else { // check for front camera ,and get the ID
                cameraId = findFrontFacingCamera();
                if (cameraId < 0) {

                    Toast.makeText(this, "No front facing camera found.",
                            Toast.LENGTH_LONG).show();
                } else {

                    Log.d("ClassScanViewBarcodeActivity",
                            "camera was found , ID: " + cameraId);
                    // camera was found , set global camera flag to true
                    isThereACamera = true;
                    // OPEN
                    globalCamera = Camera.open(cameraId);

                    // pass surfaceView to CameraPreview
                    newCameraPreview = new CameraPreview(this, globalCamera);
                    // pass CameraPreview to Layout
                    frameLayoutBarcodeScanner.addView(newCameraPreview);
                    try {
                        globalCamera
                                .setPreviewDisplay(surfaceViewBarcodeScanner
                                        .getHolder());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    // PREVIEW
                    globalCamera.startPreview();

                    Log.d("ClassScanViewBarcodeActivity",
                            "camera opened & previewing");
                }
            }// end else ,check for front camera
        }// end try
        catch (Exception exc) {

            // in case of exception release resources & cleanup
            if (globalCamera != null) {
                globalCamera.stopPreview();
                globalCamera.setPreviewCallback(null);
                globalCamera.release();
                globalCamera = null;

            }
            Log.d("ClassScanViewBarcodeActivity initializeGlobalCamera() exception:",
                    exc.getMessage());
        }// end catch
    }

    // onCreate, instantiates layouts & surfaceView used for video preview
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_barcode_vin_scanner);
        Log.d("ClassScanViewBarcodeActivity", "onCreate ");

        // create surfaceView for previewing of camera image
        frameLayoutBarcodeScanner = (FrameLayout) findViewById(R.id.FrameLayoutForPreview);
        surfaceViewBarcodeScanner = (SurfaceView) findViewById(R.id.surfaceViewBarcodeScanner);

        initializeGlobalCamera();

        // create text area & scan button
        VINtext = (TextView) findViewById(R.id.mytext);
        scanButton = findViewById(R.id.webbutton);
        // on click listener, onClick take a picture
        scanButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {

                    // if true take a picture
                    if (isThereACamera) {
                        Log.d("ClassScanViewBarcodeActivity",
                                "setOnClickListener() isThereACamera: "+ isThereACamera);

                        //set picture format to JPEG, everytime makesure JPEg callback is called 
                         Parameters parameters = globalCamera.getParameters();              
                         parameters.setPictureFormat(ImageFormat.JPEG);
                         globalCamera.setParameters(parameters);                         
                         //take pic , should call Callback 
                        globalCamera.takePicture(null, null, jpegCallback);
                        // wait 1 sec , than start preview again
                        Thread.sleep(1000);
                        //STOP
                        globalCamera.stopPreview();
                        //start previewing again onthe SurfaceView in case use wants to take another pic/scan
                        globalCamera.startPreview();

                    }

                }// end try
                catch (Exception exc) {

                    // in case of exception release resources & cleanup
                    if (globalCamera != null) {
                        globalCamera.stopPreview();
                        globalCamera.setPreviewCallback(null);
                        globalCamera.release();
                        globalCamera = null;

                    }
                    Log.d("ClassScanViewBarcodeActivity setOnClickListener() exceprtion:",
                            exc.getMessage());
                }// end catch

            }// end on Click
        });// end OnClickListener() implementation

    }// end onCreate

    @Override
    protected void onResume() {

        Log.d("ClassScanViewBarcodeActivity, onResume() globalCamera:",
                String.valueOf(globalCamera));

        if (globalCamera != null) {
            // START PREVIEW
            globalCamera.startPreview();
        } else {
            initializeGlobalCamera();
        }

        super.onResume();
    }

    @Override
    protected void onStop() {

        if (globalCamera != null) {
            globalCamera.stopPreview();
            globalCamera.setPreviewCallback(null);
            globalCamera.release();
            globalCamera = null;
        }
        super.onStop();
    }

    //callback used by takePicture()
    PictureCallback jpegCallback = new PictureCallback() {



        public void onPictureTaken(byte[] imgData, Camera camera) {
            BinaryBitmap bitmap = null;
            try {



                Log.d("ClassScanViewBarcodeActivity" ,"onPictureTaken()");

                //save image to sd card 
                savePicture(imgData);

                // get the bitmap from camera imageData
                bmpOfTheImageFromCamera = BitmapFactory.decodeByteArray(
                        imgData, 0, imgData.length);


                if (bmpOfTheImageFromCamera != null) {
                    //Galaxy S3 , incorrect rotation issue rotate to correct rotation
                    Matrix matrix = new Matrix();
                    matrix.postRotate(90);
                    Bitmap rotatedBitmap = Bitmap.createBitmap(bmpOfTheImageFromCamera, 0, 0, bmpOfTheImageFromCamera.getWidth(), bmpOfTheImageFromCamera.getHeight(), matrix, true);
                    // convert bitmap to binary bitmap
                    bitmap = cameraBytesToBinaryBitmap(rotatedBitmap);


                    if (bitmap != null) {
                        // decode the VIN
                        String VIN = decodeBitmapToString(bitmap);
                        Log.d("***ClassScanViewBarcodeActivity ,onPictureTaken(): VIN ",
                                VIN);
                        VINtext.setText(VIN);
                    } else {
                        Log.d("ClassScanViewBarcodeActivity ,onPictureTaken(): bitmap=",String.valueOf(bitmap));

                    }
                } else {
                    Log.d("ClassScanViewBarcodeActivity , onPictureTaken(): bmpOfTheImageFromCamera = ",
                            String.valueOf(bmpOfTheImageFromCamera));

                }
            }// end try

            catch (Exception exc) {
                exc.getMessage();

                Log.d("ClassScanViewBarcodeActivity , scanButton.setOnClickListener(): exception = ",
                        exc.getMessage());
            }

        }// end onPictureTaken()
    };// jpegCallback implementation


    /*
     * created savePicture(byte [] data) for testing 
     */
    public void savePicture(byte [] data)
    {
        Log.d( "ScanVinFromBarcodeActivity " , "savePicture(byte [] data)");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoFile = "Picture_"+counter+"_"+ date + ".jpg";

        File sdDir = Environment
                  .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);


        String filename =sdDir + File.separator + photoFile;

        File pictureFile = new File(filename);

        try {
          FileOutputStream fos = new FileOutputStream(pictureFile);
          fos.write(data);
          fos.close();

          Toast.makeText(this, "New Image saved:" + photoFile,
              Toast.LENGTH_LONG).show();

        } catch (Exception error) {
            Log.d( "File not saved: " , error.getMessage());
          Toast.makeText(this, "Image could not be saved.",
              Toast.LENGTH_LONG).show();
        }
        counter++;
      }



    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
                Log.d("ClassScanViewBarcodeActivity , findFrontFacingCamera(): ",
                        "Camera found");
                cameraId = i;
                break;
            }
        }
        return cameraId;
    }// end findFrontFacingCamera()

    @Override
    protected void onPause() {
        if (globalCamera != null) {
            globalCamera.stopPreview();
            globalCamera.setPreviewCallback(null);
            globalCamera.release();
            globalCamera = null;
        }
        super.onPause();
    }// end onPause()

    public String decodeBitmapToString(BinaryBitmap bitmap) {
        Reader reader = null;
        Result result = null;
        String textResult = null;
        try {

            reader = new MultiFormatReader();
            if (bitmap != null) {
                result = reader.decode(bitmap);
                if (result != null) {
                    textResult = result.getText();
                } else {
                    Log.d("ClassScanViewBarcodeActivity , String decodeBitmapToString (BinaryBitmap bitmap): result = ",
                            String.valueOf(result));
                }
            } else {
                Log.d("ClassScanViewBarcodeActivity , String decodeBitmapToString (BinaryBitmap bitmap): bitmap = ",
                        String.valueOf(bitmap));
            }
            /*
             * byte[] rawBytes = result.getRawBytes(); BarcodeFormat format =
             * result.getBarcodeFormat(); ResultPoint[] points =
             * result.getResultPoints();
             */

        } catch (NotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ChecksumException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        return textResult;
    }// end decodeBitmapToString (BinaryBitmap bitmap)

    public BinaryBitmap cameraBytesToBinaryBitmap(Bitmap bitmap) {
        BinaryBitmap binaryBitmap = null;
        if (bitmap != null) {

            int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
            bitmap.getPixels(pixels, 0, 0, bitmap.getWidth() - 1,
                    bitmap.getHeight() - 1, bitmap.getWidth(),
                    bitmap.getHeight());

            RGBLuminanceSource source = new RGBLuminanceSource(
                    bitmap.getWidth(), bitmap.getHeight(), pixels);

            HybridBinarizer bh = new HybridBinarizer(source);
            binaryBitmap = new BinaryBitmap(bh);
        } else {
            Log.d("ClassScanViewBarcodeActivity , cameraBytesToBinaryBitmap (Bitmap bitmap): bitmap = ",
                    String.valueOf(bitmap));
        }

        return binaryBitmap;
    }

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    /*
     * The method getScreenOrientation() return screen orientation either
     * landscape or portrait. IF width < height , than orientation = portrait,
     * ELSE landscape For backwards compatibility we use to methods to detect
     * the orientation. The first method is for API versions prior to 13 or
     * HONEYCOMB.
     */
    public int getScreenOrientation() {

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // if API version less than 13
        Display getOrient = getWindowManager().getDefaultDisplay();
        int orientation = Configuration.ORIENTATION_UNDEFINED;

        if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
            // Do something for API version less than HONEYCOMB

            if (getOrient.getWidth() == getOrient.getHeight()) {
                orientation = Configuration.ORIENTATION_SQUARE;
            } else {
                if (getOrient.getWidth() < getOrient.getHeight()) {
                    orientation = Configuration.ORIENTATION_PORTRAIT;
                } else {
                    orientation = Configuration.ORIENTATION_LANDSCAPE;
                }
            }
        } else {
            // Do something for API version greater or equal to HONEYCOMB

            Point size = new Point();
            this.getWindowManager().getDefaultDisplay().getSize(size);
            int width = size.x;
            int height = size.y;

            if (width < height) {
                orientation = Configuration.ORIENTATION_PORTRAIT;
            } else {
                orientation = Configuration.ORIENTATION_LANDSCAPE;
            }
        }

        return orientation;

    }// end getScreenOrientation()
}// end class ScanVinFromBarcodeActivity

用于在 SurfaceView 上顯示實(shí)時(shí)攝像頭的預(yù)覽類 (CameraPreview.java):

package com.ty.tyownerspoc.barcode;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.hardware.Camera.CameraInfo;

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private Context context;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;
        this.context = context;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the
        // preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {

        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }
                Camera.Parameters p = mCamera.getParameters();

        // get width & height of the SurfaceView
        int SurfaceViewWidth = this.getWidth();
        int SurfaceViewHeight = this.getHeight();

        List<Size> sizes = p.getSupportedPreviewSizes();
         Size optimalSize = getOptimalPreviewSize(sizes, SurfaceViewWidth, SurfaceViewHeight);


        // set parameters
        p.setPreviewSize(optimalSize.width, optimalSize.height);

        /*rotate the image by 90 degrees clockwise , in order to correctly displayed the image , images seem to be -90 degrees (counter clockwise) rotated 
         * I even tried setting it to  p.setRotation(0); , but still no effect.
         */
        mCamera.setDisplayOrientation(90);

        mCamera.setParameters(p);

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e) {
            Log.d("CameraPreview ,  surfaceCreated() , orientation: ",
                    String.valueOf(e.getMessage()));
        }
    }// end surfaceChanged()
     static Size getOptimalPreviewSize(List <Camera.Size>sizes, int w, int h) {
            final double ASPECT_TOLERANCE = 0.1;
            final double MAX_DOWNSIZE = 1.5;

            double targetRatio = (double) w / h;
            if (sizes == null) return null;

            Size optimalSize = null;
            double minDiff = Double.MAX_VALUE;

            int targetHeight = h;

            // Try to find an size match aspect ratio and size
            for (Camera.Size size : sizes) {
              double ratio = (double) size.width / size.height;
              double downsize = (double) size.width / w;
              if (downsize > MAX_DOWNSIZE) {
                //if the preview is a lot larger than our display surface ignore it
                //reason - on some phones there is not enough heap available to show the larger preview sizes
                continue;
              }
              if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
              if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
              }
            }
            // Cannot find the one match the aspect ratio, ignore the requirement
            //keep the max_downsize requirement
            if (optimalSize == null) {
              minDiff = Double.MAX_VALUE;
              for (Size size : sizes) {
                double downsize = (double) size.width / w;
                if (downsize > MAX_DOWNSIZE) {
                  continue;
                }
                if (Math.abs(size.height - targetHeight) < minDiff) {
                  optimalSize = size;
                  minDiff = Math.abs(size.height - targetHeight);
                }
              }
            }
            //everything else failed, just take the closest match
            if (optimalSize == null) {
              minDiff = Double.MAX_VALUE;
              for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                  optimalSize = size;
                  minDiff = Math.abs(size.height - targetHeight);
                }
              }
            }
            return optimalSize;
          }

}//end Preview class

ScanVinFromBarcodeActivity"活動的布局 (activity_barcode_vin_scanner.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="20dip" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="20dip"
        android:text="@string/decode_label"
        android:textColor="@color/mbackground1" />

    <TextView
        android:id="@+id/mytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/mbackground2"
        android:gravity="center_horizontal"
        android:padding="20dip"
        android:textColor="@color/mytextcolor" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="20dip"
        android:text="@string/continue_label"
        android:textColor="@color/mytextcolor" />

    <Button
        android:id="@+id/webbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/web_button"
        android:textColor="@color/mytextcolor" />

    <FrameLayout
    android:id="@+id/FrameLayoutForPreview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1">

        <SurfaceView
            android:id="@+id/surfaceViewBarcodeScanner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </FrameLayout>
</LinearLayout>

任何幫助將不勝感激.

謝謝

Updated & working onTakePicturen method, the that works , the PictureCallback returns (stopPreview & StartPreview were moved to inside this method in its finally block).


    public void onPictureTaken(byte[] imgData, Camera camera) {
        BinaryBitmap bitmap;
        try {



            Log.d("ClassScanViewBarcodeActivity" ,"onPictureTaken()");

            //save image to sd card 
            savePicture(imgData);

            // get the bitmap from camera imageData

            BitmapFactory.Options options = new BitmapFactory.Options();
              options.inSampleSize = 8; 
              //down sample
            bmpOfTheImageFromCamera = BitmapFactory.decodeByteArray(
                    imgData, 0, imgData.length,options);


            if (bmpOfTheImageFromCamera != null) {

                Log.d("***ClassScanViewBarcodeActivity ,onPictureTaken(): bmpOfTheImageFromCamera getByteCount(): ",
                        String.valueOf(bmpOfTheImageFromCamera.getByteCount()));
                //Galaxy S3 , incorrect rotation issue rotate to correct rotation
                /*Matrix matrix = new Matrix();
                matrix.postRotate(90);
                Bitmap rotatedBitmap = Bitmap.createBitmap(bmpOfTheImageFromCamera, 0, 0, bmpOfTheImageFromCamera.getWidth(), bmpOfTheImageFromCamera.getHeight(), matrix, true);*/
                // convert bitmap to binary bitmap
                bitmap = cameraBytesToBinaryBitmap(bmpOfTheImageFromCamera);


                if (bitmap != null) {
                    // decode the VIN
                    String VIN = decodeBitmapToString(bitmap);
                    Log.d("***ClassScanViewBarcodeActivity ,onPictureTaken(): VIN ",
                            VIN);
                    VINtext.setText(VIN);
                } else {
                    Log.d("ClassScanViewBarcodeActivity ,onPictureTaken(): bitmap=",String.valueOf(bitmap));

                }
            } else {
                Log.d("ClassScanViewBarcodeActivity , onPictureTaken(): bmpOfTheImageFromCamera = ",
                        String.valueOf(bmpOfTheImageFromCamera));

            }


        }// end try

        catch (Exception exc) {
            exc.getMessage();

            Log.d("ClassScanViewBarcodeActivity , scanButton.setOnClickListener(): exception = ",
                    exc.getMessage());
        }

        finally
        {
            globalCamera.stopPreview();
            //start previewing again onthe SurfaceView in case use wants to take another pic/scan
            globalCamera.startPreview();
        }

    }// end onPictureTaken()
};// jpegCallback implementation

推薦答案

我能找到的唯一可能是罪魁禍?zhǔn)椎氖牵?jpegCallback 返回之前再次開始預(yù)覽.根據(jù) javadoc,這是不允許的:

The only thing I can find that might be the culprit is that you're starting the preview again before the jpegCallback has returned. According to the javadoc, this is not allowed:

調(diào)用此方法后,在 JPEG 回調(diào)返回之前,不得調(diào)用 startPreview() 或拍攝另一張照片.

After calling this method, you must not call startPreview() or take another picture until the JPEG callback has returned.

回調(diào)實(shí)際上是放在 UI 線程隊(duì)列中 - 它將在您的 Thread.sleep() 中暫停,并且同一個(gè)線程將調(diào)用 stopPreview() 并且startPreview() 在真正進(jìn)入回調(diào)之前.一般來說,如果你在 UI 線程上調(diào)用 Thread.sleep() - 你做錯(cuò)了.因此,希望如果您刪除 sleep() 并將其后的內(nèi)容放入 jpegCallback 您的問題應(yīng)該得到解決.

The callback is actually put on the UI thread queue - which will be suspended in your Thread.sleep() and the same thread will have called stopPreview() and startPreview() before actually coming to the callback. Generally speaking, if you call Thread.sleep() on the UI thread - you're doing it wrong. So, hopefully if you remove the sleep() and put what comes after it in the jpegCallback your problem should be solved.

這篇關(guān)于Android camera , onPictureTaken(byte[] imgData, Camera camera) 方法 &amp;PictureCallback 從未調(diào)用過的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

Why does the android emulator camera stop unexpectedly?(為什么android模擬器相機(jī)會意外停止?)
Understanding the libGDX Projection Matrix(了解 libGDX 投影矩陣)
QR code reading with camera - Android(使用相機(jī)讀取二維碼 - Android)
IP camera with OpenCv in Java(Java中帶有OpenCv的IP攝像頭)
Android mock Camera(Android 模擬相機(jī))
Multiple cameras in libgdx ( probably similar in other frameworks )(libgdx 中的多個(gè)攝像頭(在其他框架中可能類似))
主站蜘蛛池模板: 粒米特测控技术(上海)有限公司-测功机_减速机测试台_电机测试台 | 成都中天自动化控制技术有限公司 | 杭州中策电线|中策电缆|中策电线|杭州中策电缆|杭州中策电缆永通集团有限公司 | 石牌坊价格石牌坊雕刻制作_石雕牌坊牌楼石栏杆厂家_山东嘉祥石雕有限公司 | 济南保安公司加盟挂靠-亮剑国际安保服务集团总部-山东保安公司|济南保安培训学校 | GAST/BRIWATEC/CINCINNATI/KARL-KLEIN/ZIEHL-ABEGG风机|亚喜科技 | 新型游乐设备,360大摆锤游乐设备「诚信厂家」-山东方鑫游乐设备 新能源汽车电池软连接,铜铝复合膜柔性连接,电力母排-容发智能科技(无锡)有限公司 | 西安展台设计搭建_西安活动策划公司_西安会议会场布置_西安展厅设计西安旭阳展览展示 | 东莞注册公司-代办营业执照-东莞公司注册代理记账-极刻财税 | 湖南档案密集架,智能,物证,移动,价格-湖南档案密集架厂家 | 北京模型公司-工业模型-地产模型-施工模型-北京渝峰时代沙盘模型制作公司 | 电表箱-浙江迈峰电力设备有限公司-电表箱专业制造商 | 深圳公司注册-工商注册公司-千百顺代理记账公司 | 亚克力制品定制,上海嘉定有机玻璃加工制作生产厂家—官网 | 翻斗式矿车|固定式矿车|曲轨侧卸式矿车|梭式矿车|矿车配件-山东卓力矿车生产厂家 | 【直乐】河北石家庄脊柱侧弯医院_治疗椎间盘突出哪家医院好_骨科脊柱外科专业医院_治疗抽动症/关节病骨伤权威医院|排行-直乐矫形中医医院 | 钢木实验台-全钢实验台-化验室通风柜-实验室装修厂家-杭州博扬实验设备 | 皮带机_移动皮带机_大倾角皮带机_皮带机厂家 - 新乡市国盛机械设备有限公司 | 西点培训学校_法式西点培训班_西点师培训_西点蛋糕培训-广州烘趣西点烘焙培训学院 | 电梯装饰-北京万达中意电梯装饰有限公司| 新疆散热器,新疆暖气片,新疆电锅炉,光耀暖通公司 | 超声波电磁流量计-液位计-孔板流量计-料位计-江苏信仪自动化仪表有限公司 | 新疆系统集成_新疆系统集成公司_系统集成项目-新疆利成科技 | 3d可视化建模_三维展示_产品3d互动数字营销_三维动画制作_3D虚拟商城 【商迪3D】三维展示服务商 广东健伦体育发展有限公司-体育工程配套及销售运动器材的体育用品服务商 | 我车网|我关心的汽车资讯_汽车图片_汽车生活! | 赛默飞Thermo veritiproPCR仪|ProFlex3 x 32PCR系统|Countess3细胞计数仪|371|3111二氧化碳培养箱|Mirco17R|Mirco21R离心机|仟诺生物 | 阿尔法-MDR2000无转子硫化仪-STM566 SATRA拉力试验机-青岛阿尔法仪器有限公司 | 磁力抛光研磨机_超声波清洗机厂家_去毛刺设备-中锐达数控 | 光谱仪_积分球_分布光度计_灯具检测生产厂家_杭州松朗光电【官网】 | 石家庄装修设计_室内家装设计_别墅装饰装修公司-石家庄金舍装饰官网 | 全国国际化学校_国际高中招生_一站式升学择校服务-国际学校网 | 重庆网站建设,重庆网站设计,重庆网站制作,重庆seo,重庆做网站,重庆seo,重庆公众号运营,重庆小程序开发 | 办公室家具公司_办公家具品牌厂家_森拉堡办公家具【官网】 | 沈阳网站建设_沈阳网站制作_沈阳网页设计-做网站就找示剑新零售 沈阳缠绕膜价格_沈阳拉伸膜厂家_沈阳缠绕膜厂家直销 | 门禁卡_智能IC卡_滴胶卡制作_硅胶腕带-卡立方rfid定制厂家 | POS机办理_个人pos机免费领取-银联pos机申请首页 | 拉力机-万能试验机-材料拉伸试验机-电子拉力机-拉力试验机厂家-冲击试验机-苏州皖仪实验仪器有限公司 | 知企服务-企业综合服务(ZiKeys.com)-品优低价、种类齐全、过程管理透明、速度快捷高效、放心服务,知企专家! | 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 | 焊接减速机箱体,减速机箱体加工-淄博博山泽坤机械厂 | 进口消泡剂-道康宁消泡剂-陶氏消泡剂-大洋消泡剂 |