3

当我按下返回或主页按钮时,我的应用程序给出错误“不幸的是 PhotoComment 已停止”。但是当我从任务管理器重新打开应用程序时,它可以工作。

这是我的 mainactivity.java

package com.cameratag;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity{

    private CameraSurfaceView cameraView;
    private ImageView imageResult;
    private ImageView imageResult2;
    private FrameLayout framenew;
    private TextView snapPhoto;
    private boolean takePicture = true;
    private Bitmap image = null;
    private String lastPreviewImgPath = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setupcamera();
    }

    public void setupcamera(){
        cameraView = new CameraSurfaceView(getApplicationContext());
        imageResult = new ImageView(getApplicationContext());
        imageResult.setBackgroundColor(Color.GRAY);

        framenew = (FrameLayout) findViewById(R.id.frame);
        snapPhoto = (TextView) findViewById(R.id.textView1);

        framenew.addView(imageResult);
        framenew.addView(cameraView);
    }

    public void captureHandler(View view){
        if(takePicture){
            cameraView.capture(jpegHandler);
        }
        else{
            takePicture = true;
            cameraView.preview();
            framenew.bringChildToFront(cameraView);
            imageResult.setImageBitmap(null);
            snapPhoto.setText("Capture");
        }
    }

    public void zoomMinusHandler(View view){
        cameraView.zoomMinus();
    }

    public void zoomPilusHandler(View view){
        cameraView.zoomPilus();
    }

    public Camera.PictureCallback jpegHandler = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub
            image = BitmapFactory.decodeByteArray(data, 0, data.length);
            imageResult.setImageBitmap(image);
            imageResult2 = imageResult; 
            LayoutParams params = imageResult.getLayoutParams();
            params.width = framenew.getWidth();
            params.height = framenew.getHeight();
            imageResult2.setLayoutParams(params);
            //framenew.bringChildToFront(imageResult);
            //snapPhoto.setText("Take Picture");
            //takePicture = false;

            File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "NNCam");
              if (!directory.exists()) {
                if (!directory.mkdirs()) {
                  //Log.e(TAG, "Failed to create storage directory.");
                }
              }

              String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date(System.currentTimeMillis()));
              String filename = "/IMG_" + timeStamp + ".jpg";
              if(image!=null){
                  saveImage(directory.getPath(),filename,image);
                  cameraView.preview();
              }



        }
    };

    public void saveImage(String path, String imgname, Bitmap image){
        try{
            FileOutputStream fos = new FileOutputStream(path+imgname);

        BufferedOutputStream  stream = new BufferedOutputStream(fos);

        image.compress(CompressFormat.JPEG, 100, stream);

        stream.flush();
        stream.close();
        }
        catch(FileNotFoundException e){

        }
        catch(IOException e){

        }
        lastPreviewImgPath = path+imgname;
        Bitmap bitmap = BitmapFactory.decodeFile(lastPreviewImgPath);
          ImageView myImageView = (ImageView)findViewById(R.id.lastPreview);
          myImageView.setImageBitmap(bitmap);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
       super.onSaveInstanceState(savedInstanceState);
            cameraView.release();
    }
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
       super.onRestoreInstanceState(savedInstanceState);
            cameraView.reconnect();
    }
    @Override
    public void onPause() {
       super.onPause();
            cameraView.release();
    }
}

这是surfaceview类

package com.cameratag;

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

import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
    private Context context;
    private SurfaceHolder mHolder;
    public Camera camera = null;
    public int zoomValue = 0;

    public CameraSurfaceView(Context context) {
        super(context);
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        Camera.Parameters parameters = camera.getParameters();  
        List<Camera.Size> sizes = parameters.getSupportedPictureSizes();  
        Camera.Size cs = sizes.get(0);
        List<Camera.Size> sizes2 = parameters.getSupportedPreviewSizes();  
        Camera.Size cs2 = sizes2.get(0);
        parameters.setPreviewSize(cs2.width, cs2.height);
        parameters.setPictureSize(cs.width, cs.height);
        camera.setParameters(parameters);
        camera.startPreview();
    }

    @Override
    public void surfaceCreated(SurfaceHolder arg0) {
        // TODO Auto-generated method stub
        camera = Camera.open();
        try {
            camera.setPreviewDisplay(mHolder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }

        int rrr = 0;
        Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        if(rotation==0)rrr=90;
        else if(rotation==1)rrr=0;
        else if(rotation==3)rrr=180;
        else rrr=270;
        camera.setDisplayOrientation(rrr);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        // TODO Auto-generated method stub
        camera.stopPreview();
        camera = null;
    }

    public void capture(Camera.PictureCallback jpegHandler){
        camera.takePicture(null, null, jpegHandler);
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int rrr = 0;
        Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        if(rotation==0)rrr=90;
        else if(rotation==1)rrr=0;
        else if(rotation==3)rrr=180;
        else rrr=270;
        //camera.stopPreview();
        camera.setDisplayOrientation(rrr);
        //camera.startPreview();

    }

    public void preview(){
        camera.startPreview();
    }
    public void reconnect(){
        try {
            camera.reconnect();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
    }

    public void zoomMinus() {
        Camera.Parameters parameters = camera.getParameters();
        // TODO Auto-generated method stub
        if(parameters.isZoomSupported()){
            if(zoomValue>0){
                zoomValue-=2;
                parameters.setZoom(zoomValue);

                if(parameters.isSmoothZoomSupported()){
                    camera.startSmoothZoom(zoomValue);
                }
                else{
                    camera.setParameters(parameters);
                }
            }
        }
    }
    public void zoomPilus() {
        Camera.Parameters parameters = camera.getParameters();  

        // TODO Auto-generated method stub
        if(parameters.isZoomSupported()){
            if(zoomValue<parameters.getMaxZoom()){
                zoomValue+=2;
                parameters.setZoom(zoomValue);

                if(parameters.isSmoothZoomSupported()){
                    camera.startSmoothZoom(zoomValue);
                }
                else{
                    camera.setParameters(parameters);
                }
            }
        }
    }

    public void release() {
        // TODO Auto-generated method stub
        camera.setPreviewCallback(null);
        camera.stopPreview();
        camera.release();
    }

}

请帮忙。

4

4 回答 4

2
 @Override
protected void onPause() {
    super.onPause();

  //        if (inPreview) {
 //         mCamera.stopPreview();
 //     }
 //     mCamera.release();
 //     mCamera = null;
 //     inPreview = false;
    mCamera.setPreviewCallback(null);
    super.onPause();
    // mCamera.stopPreview();
}
于 2013-07-26T13:27:34.540 回答
0

尝试将您的发布代码放在 try catch 块中

try{
  if (camera != null){
    camera.setPreviewCallback(null);
    camera.stopPreview();
    camera.release();
  }
}
于 2013-07-24T05:39:39.013 回答
0

我已经找到了适合自己的解决方案。您只需要将 surfaceDestroyed 方法更改为此。

@Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        // TODO Auto-generated method stub
        try{
        camera.stopPreview();
        camera.release();
        camera = null;
        }
        catch(NullPointerException e){
            //e.printStackTrace();
        }
    }

和 onRestoreInstanceState 到这个。

@Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
       super.onRestoreInstanceState(savedInstanceState);
            cameraView = null;
            setupcamera();
            //cameraView.reconnect();
    }
于 2013-07-24T05:58:29.063 回答
0

我遇到了类似的问题,诀窍是还要在 onResume() 中设置相机。

问题是应用程序不会在您每次使用后退按钮进入活动时调用 onCreate(),有时它只是暂停活动。每当活动返回前台时都会调用 onResume() 并且是设置相机的更可靠的地方。

@Override
protected void onResume()
{
    super.onResume();
    if( camera == null )
    {
        camera = Camera.open();
    }
}
于 2013-07-23T20:46:57.810 回答