自定义相机无论如何都不工作

时间:2014-02-22 00:14:07

标签: java android android-camera

我正在尝试各种方式为Android制作相机应用。我尝试了很多指南(还有很多关于这个问题的答案),但是在每一个指导之后,似乎都没有任何指导。

我也尝试了Google文档,但它没有用,无论如何我在AndroidManifest.xml中拥有所有必需的权限

这是我的最后一次尝试

    package com.ithoughtugnu.photoxor;

    import java.io.IOException;
    import java.util.ArrayList;

    import android.app.Activity;
    import android.graphics.PixelFormat;
    import android.hardware.Camera;
    import android.hardware.Camera.PictureCallback;
    import android.hardware.Camera.Size;
    import android.os.Bundle;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.ImageView;

    public class Custom_CameraActivity extends Activity implements
    SurfaceHolder.Callback {

/* VARIABILI PRIVATE */
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
private boolean mPreviewRunning;

@SuppressWarnings("deprecation")
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_camera);
    addListenerOnButton();


    getWindow().setFormat(PixelFormat.TRANSLUCENT); // aggiungo il
                                                    // traslucido
    requestWindowFeature(Window.FEATURE_NO_TITLE); // no barra titolo
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN); // full screen
    mSurfaceView = (SurfaceView) findViewById(R.id.camera_surface); 
    mSurfaceHolder = mSurfaceView.getHolder(); // recupero l'holder della
                                                // SurfaceView
    mSurfaceHolder.addCallback(this); // faccio la bind con la nostra
                                        // activity
    mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

}

public void addListenerOnButton() {
    ImageView buttonPicture = (ImageView) findViewById(R.id.imageView1);
    buttonPicture.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mCamera.takePicture(null, null, jpegCallback);
        }
    });
}

PictureCallback jpegCallback = new PictureCallback() {
    public void onPictureTaken(byte[] _data, Camera _camera) {
        // riparte la preview della camera
        mCamera.startPreview();

    }
};

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    if (mPreviewRunning)
        mCamera.stopPreview();

    // setto le preferenze
    Camera.Parameters p = mCamera.getParameters(); // prendo le preferenze
                                                    // della camera
    p.setPreviewSize(arg2, arg3);
    ArrayList<Size> list = (ArrayList<Size>) p.getSupportedPictureSizes();
    int picture_width = list.get(list.size() - 1).width;
    int picture_height = list.get(list.size() - 1).height;
    p.setPictureSize(picture_width, picture_height); 
    p.setJpegQuality(80); // qualità compressione JPEG

    // salvo le pref
    mCamera.setParameters(p);
    try {
        // lancio la preview
        mCamera.setPreviewDisplay(arg0);
        mCamera.startPreview();
        mPreviewRunning = true;
    } catch (IOException e) {
        // gestione errore
    }

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    mCamera = Camera.open();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    mCamera.stopPreview();
    mPreviewRunning = false;
    mCamera.release();

}
    }

activity_custom_camera.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

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

 <SurfaceView android:id="@+id/camera_surface"
                    android:layout_width="fill_parent" 
                    android:layout_height="fill_parent"
                    android:layout_weight="1">
            </SurfaceView>

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="16dp"
    android:clickable="true"
    android:contentDescription="@string/capture"
    android:onClick="captureImageClick"
    android:src="@drawable/capture" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="18dp"
    android:layout_marginTop="18dp"
    android:contentDescription="@string/change_camera"
    android:src="@drawable/revert" />

<ImageView
    android:id="@+id/imageSettings"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/imageView2"
    android:layout_marginRight="18dp"
    android:contentDescription="@string/settings"
    android:src="@drawable/settings_icon2" />

<ImageView
    android:id="@+id/imageGallery"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView2"
    android:layout_alignTop="@+id/imageView1"
    android:contentDescription="@string/gallery"
    android:src="@drawable/gallery2" />

<ImageView
    android:id="@+id/imageEffects"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imageView1"
    android:layout_alignRight="@+id/imageSettings"
    android:contentDescription="@string/effects"
    android:src="@drawable/effects" />
    </RelativeLayout>

我没有看到Camera Perspective,如果按下按钮Capture我在Logcat中收到了这些错误

    02-22 01:07:39.567: W/Camera(8264): Camera server died!

    02-22 01:07:39.567: W/Camera(8264): ICamera died    

    02-22 01:07:39.577: E/Camera(8264): Error 100

如果我再次执行1-2次,我会在Logcat和应用程序崩溃中收到大量红色消息。 对于我尝试的每个教程都会发生这种情况,我不知道为什么。

N.B。我正在使用三星Galaxy S Advance,但我在Nexus 5和应用程序崩溃时也试过它,然后让我有可能按下捕获按钮。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这里有几条建议。

  1. Camera.open() Activity / Fragment方法
  2. 上执行此繁重的相机onResume()
  3. 您似乎没有检查相机当前是否可用。每次你请求相机时都不能指望它可以随时为你服务。
  4. 这可能与相机实例的正确初始化无关。
  5. 以下是我的示例代码似乎正在处理并使用上述建议。检查特别是表面方法似乎是混合表面方法的工作。

    public class NewItemCameraFragment extends Fragment{
    
        private static final String TAG_STRING = NewItemCameraFragment.class.toString();
    
        private Camera mCamera;
        private SurfaceView mSurfaceView;
        private Button mTakeButton;
        private FrameLayout mProgressLayout;
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_item_camera, null, false);
    
            mProgressLayout = (FrameLayout) view.findViewById(R.id.item_camera_progress);
            mProgressLayout.setVisibility(View.INVISIBLE);
    
            mTakeButton = (Button) view.findViewById(R.id.item_camera_button);
            mTakeButton.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    if (mCamera != null) {
                        mCamera.takePicture(mShutterCallback, null, mPictureCallback);
                    }
    
                }
            });
    
            mSurfaceView = (SurfaceView) view.findViewById(R.id.item_camera_surfaceview);
            SurfaceHolder holder = mSurfaceView.getHolder();
            holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            holder.addCallback(new Callback() {
    
                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    // TODO Auto-generated method stub
                    if (mCamera != null) {
                        mCamera.stopPreview();
                    }
                }
    
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    // TODO Auto-generated method stub
                    if (mCamera != null) {
                        try {
                            mCamera.setPreviewDisplay(holder);
                            mCamera.setDisplayOrientation(90);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Log.d(TAG_STRING, "Error setting up preview display " + e);
                        }
                    }
                }
    
                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width,
                        int height) {
    
                    if (mCamera == null) return;
    
                    Camera.Parameters parameters = mCamera.getParameters();
                    Size s = getBestSupportedSize(parameters.getSupportedPreviewSizes(), width, height);
                    parameters.setPreviewSize(s.width, s.height);
                    s = getBestSupportedSize(parameters.getSupportedPreviewSizes(), width, height);
                    parameters.setPictureSize(s.width, s.height);
                    mCamera.setParameters(parameters);
    
                    try {
                        mCamera.startPreview();
                    } catch (Exception e) {
                        Log.d(TAG_STRING, "Could not start the preview " + e);
                        mCamera.release();
                        mCamera = null;
                    }
    
                }
            });
    
            return view;
        }
    
        private Camera.ShutterCallback mShutterCallback = new ShutterCallback() {
    
            @Override
            public void onShutter() {
                mProgressLayout.setVisibility(View.VISIBLE);
            }
        };
    
    
        private Camera.PictureCallback mPictureCallback = new PictureCallback() {
    
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                String filename = UUID.randomUUID().toString() + ".jpg";
                FileOutputStream fos = null;
                boolean success = true;
    
                try {
                    fos = getActivity().openFileOutput(filename, Context.MODE_PRIVATE);
                    fos.write(data);
                } catch (Exception e) {
                    Log.d(TAG_STRING, "Error writing to file " + e);
                } finally {
                    try {
                        if (fos != null)  fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        success = false;
                    }
                }
    
                if (success) { Log.i(TAG_STRING, "File saved at " + filename); }
                getActivity().finish();
            }
        };
    
        private Size getBestSupportedSize(List<Size> sizes, int width, int height) {
            Size bestSize = sizes.get(0);
            int largestArea = bestSize.width * bestSize.height;
    
            for (Size size : sizes) {
                int area = size.width * size.height;
                if (largestArea < area) {
                    bestSize = size;
                    largestArea = area;
                }
            }
    
            return bestSize;
        }
    
    
        @Override
        public void onResume() {
            super.onResume();
            mCamera = Camera.open();
        }
    
    
        @Override
        public void onPause() {
            super.onPause();
            if (mCamera != null) {
                mCamera.release();
                mCamera = null;
            }
        }
    }
    

    更新了布局以清除问题。

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent" >
    
    <LinearLayout 
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">
    
        <SurfaceView 
            android:id="@+id/item_camera_surfaceview"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:layout_weight="1"/>
    
        <Button 
            android:id="@+id/item_camera_button"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="@string/item_camera_button_text"/>
    
    </LinearLayout>
    
    <FrameLayout 
        android:id="@+id/item_camera_progress"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true">
    
        <ProgressBar 
            style="@android:style/Widget.ProgressBar.Large"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_gravity="center"/>
    
    </FrameLayout>
    
    </FrameLayout>