0

我的示例相机代码适用于 14 以下的 android API 级别

当我在 API 级别 14 或更高级别尝试时,它会引发空指针异常。请你能告诉我哪里出错了。

protected void onStart() {
    super.onStart();
    cam= Camera.open();
    Log.e("msg", cam+"");
    mp=new MyPreview(getApplicationContext(), cam);
    frame1.addView(mp);
    Toast.makeText(getApplicationContext(), "Camera open", 5).show();
}

Mypreview是一个扩展 SurfaceView 并实现 SurfaceHolder.CallBack 的类

代码是:

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MyPreview extends SurfaceView implements SurfaceHolder.Callback {
private Camera _cam;
private SurfaceHolder sh;

@SuppressWarnings("deprecation")
public MyPreview(Context context, Camera _cam) {
    super(context);
    this._cam = _cam;
    sh=getHolder();
    sh.addCallback(this);
    sh.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub

    Camera.Parameters cp = _cam.getParameters();
    cp.setPreviewSize(width, height);

    cp.setFlashMode(Parameters.FLASH_MODE_AUTO);


    _cam.setParameters(cp);
    _cam.setDisplayOrientation(90);

    _cam.startPreview();

}



@Override
public void surfaceCreated(SurfaceHolder holder) {
    try {
        _cam.setPreviewDisplay(holder);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    _cam.stopPreview();
}

}
4

0 回答 0