自定义相机预览在Android 4.1中不起作用?

时间:2014-04-11 09:02:59

标签: android camera preview

我在android中创建自定义相机视图。但是当我打开相机片段时,不是相机预览是黑屏但是android 2.3.0正在工作但是android 4.1及以上版本无效。我的代码在下面。

enter image description here

我的TakeCameraFragment代码如下::

public class TakeCameraFragment extends Fragment {
    Camera mCamera ;
     CameraPreview mCameraPreview;

    protected static final int MEDIA_TYPE_IMAGE = 0;
    static String FilePAth = "";
    Button takePicture;
    static String base64string = "";

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

        final View rootView = inflater.inflate(R.layout.camerafragment,
                container, false);

        mCamera = getCameraInstance();

        Log.v("log_tag", "mCamera :: " + mCamera);

        mCameraPreview = new CameraPreview(getActivity(), mCamera);
        FrameLayout preview = (FrameLayout) rootView
                .findViewById(R.id.camera_preview_fragment);

        preview.addView(mCameraPreview);

        takePicture = (Button) rootView
                .findViewById(R.id.btnTakePicturefragment);
        takePicture.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                mCamera.takePicture(null, null, mPictureframent);

            }
        });

        return rootView;

    }

    public boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        releaseCamera();
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release(); // release the camera for other applications
            mCamera = null;
        }
    }

    private Camera getCameraInstance() {
        Camera mCamera = null;
        try {

            mCamera = Camera.open();

        } catch (Exception e) {
            // cannot get camera or does not exist

            releaseCamera();
        }
        return mCamera;
    }

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraAppFragment");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {

                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());

        FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_fragment_"
                + timeStamp + ".jpg";

        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_fragment_" + timeStamp + ".jpg");

        return mediaFile;
    }

    PictureCallback mPictureframent = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                return;
            }
            try {

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

                FragmentManager fm = getFragmentManager();

                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                SetPictureImageFragment fm2 = new SetPictureImageFragment();
                fragmentTransaction.replace(R.id.relative_camerafragment_id,
                        fm2, "HELLO");
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                Bundle bundle = new Bundle();
                bundle.putByteArray("position", data);
                fm2.setArguments(bundle);
                mCamera.startPreview();


            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

}

相机预览代码::

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;
     Boolean isPreviewRunning = true; 


    // Constructor that obtains context and camera
     public CameraPreview(Context context, Camera camera) {
            super(context);
            mCamera = camera;

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

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        /*try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
            //mCamera.setDisplayOrientation(90);
        } catch (IOException e) {
            // left blank for now
        }*/
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        //mCamera.stopPreview();
    //  mCamera.release();
         if (mCamera != null)
            {
                mCamera.stopPreview();
                mCamera.release();
            }
    }

    /*@Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
            int width, int height) {
        // start preview with new settings

        try {
            mCamera.stopPreview();
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
            //mCamera.setDisplayOrientation(90);
        } catch (Exception e) {
            // intentionally left blank for a test
        }
    }*/

      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 (mSurfaceHolder.getSurface() == null){
              // preview surface does not exist
              return;
            }

            // stop preview before making changes
            if(isPreviewRunning)
            {
              mCamera.stopPreview();
            }

            Parameters parameters = mCamera.getParameters();

            WindowManager windo =  (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            Display display = windo.getDefaultDisplay();

            if(display.getRotation() == Surface.ROTATION_0)
            {
                parameters.setPreviewSize(h,w);          
                mCamera.setDisplayOrientation(90);

            }

            if(display.getRotation() == Surface.ROTATION_90)
            {
                parameters.setPreviewSize(w, h);            

            }

            if(display.getRotation() == Surface.ROTATION_180)
            {
                parameters.setPreviewSize(h, w);  
             //   mCamera.setDisplayOrientation(270);

            }

            if(display.getRotation() == Surface.ROTATION_270)
            {
                parameters.setPreviewSize(w, h);
                mCamera.setDisplayOrientation(180);

            }
            // set preview size and make any resize, rotate or
            // reformatting changes here

            // start preview with new settings

//          mCamera.setParameters(parameters);
            try {
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();
                isPreviewRunning = true;

            } catch (Exception e){
                Log.d("log", "Error starting camera preview: " + e.getMessage());
            }
        }

      @Override
        protected void onMeasure(int widthSpec, int heightSpec) {
            int previewWidth = MeasureSpec.getSize(widthSpec);
            int previewHeight = MeasureSpec.getSize(heightSpec);

            //Get the padding of the border background
            int hPadding = getPaddingLeft() + getPaddingRight();
            int vPadding = getPaddingTop() + getPaddingBottom();

            //Resize the preview frame with correct aspect ratio
            previewWidth += hPadding;
            previewHeight -= vPadding;

            //Add the padding of the border.
            previewWidth += hPadding;
            previewHeight += vPadding;

            //Ask children to follow the new preview dimension
            super.onMeasure(MeasureSpec.makeMeasureSpec(previewWidth, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(previewHeight, MeasureSpec.EXACTLY));
        }
}

下面我的Xml代码::

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relative_camerafragment_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/white"
    android:descendantFocusability="blocksDescendants"
     >


        <FrameLayout
            android:id="@+id/camera_preview_fragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/conform" >
        </FrameLayout>


    <Button
        android:id="@+id/btnTakePicturefragment"
        android:layout_width="60dip"
        android:layout_height="60dip"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="18dp"
        android:background="@drawable/camera" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

你应该写Camera.startPreview();添加此行后它会起作用