2013-07-15 93 views
0

我正在開發此應用程序,它需要訪問相機。我已經很好地訪問了它。但有兩個問題。 當手機垂直時,預覽全部拉伸。其次,當我恢復應用程序時,相機預覽不可見。 camera.open()函數確實會打開相機,但我無法看到預覽。我已經嘗試了論壇上提供的所有幫助,但實際上並沒有解決我的問題。相機預覽在應用程序恢復後不可見

- 預先感謝!

//Camera Activity file 

@SuppressLint("SimpleDateFormat") 
public class CameraActivity extends Activity { 
private Camera mCamera; 
private CameraPreview mPreview; 
private FrameLayout preview; 
private Button bCapture; 
private Button bGallery; 
private static final String TAG = "CameraActivity"; 
private static final int PICK_IMAGE_REQUEST = 1; 
private TextView tvCheck; 
public final static String EXTRA_MESSAGE = "com.epfl.mycamera.MESSAGE";  
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    getWindow().requestFeature(Window.FEATURE_NO_TITLE); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    setContentView(R.layout.activity_camera); 
    if (checkCameraHardware(getBaseContext())){ 
     // Create an instance of Camera 
     mCamera = getCameraInstance(); 
     // Create our Preview view and set it as the content of our activity. 
     mPreview = new CameraPreview(this, mCamera, CameraActivity.this); 
     preview = (FrameLayout) findViewById(R.id.camera_preview); 
     preview.addView(mPreview); 
     //Adding Camera Button 
     bCapture = (Button) findViewById(R.id.bCapture); 
     //Button Listener for storing images 
     bCapture.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       mCamera.takePicture(null, null, null, jpegCallback); 
       mCamera.startPreview(); 
       Log.d(TAG, "takePicture"); 
      } 
     }); 
     //Adding Gallery Button 
     bGallery = (Button) findViewById (R.id.bGallery); 
     bGallery.setOnClickListener(new View.OnClickListener() {   
      @Override 
      public void onClick(View v) { 
       tvCheck = (TextView) findViewById (R.id.tvCheck); 
       selectImageFromGallery(); 
      } 
     }); 
    } 
     Log.d(TAG, "OnCreate"); 
} 
/******************************************************************/ 

public void selectImageFromGallery() { 
    Intent intent = new Intent(); 
    intent.setType("image/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST); 
} 

@Override 
protected void onActivityResult(int aRequestCode, int aResultCode, Intent aData) { 
    switch (aRequestCode) { 
     case PICK_IMAGE_REQUEST: 
      handleImage(aData); 
      break; 
     default: 
      tvCheck.setText("You can only select images."); 
      break; 
    } 
    super.onActivityResult(aRequestCode, aResultCode, aData); 
} 


private void handleImage(Intent aData) { 
    if ((aData != null) && (aData.getData() != null)) { 
     Uri selectedImage = aData.getData(); 
     String[] filePathColumn = {MediaColumns.DATA}; 
     Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 
     cursor.moveToFirst(); 
     Log.d("ImageActivity", "After extracting file Path"); 
     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     String picturePath = cursor.getString(columnIndex); 
     cursor.close(); 
     Log.d("ImageActivity", "After closing the cursor"); 
     setContentView(R.layout.activity_image_old); //setting the view to the image 
     ImageView imgView = (ImageView) findViewById(R.id.ivGallery); 
     imgView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 
     Button bLiveCamera = (Button) findViewById(R.id.bCameraPreview); 
     bLiveCamera.setOnClickListener(new View.OnClickListener() {   
      @Override 
      public void onClick(View v) { 
       setContentView(R.layout.activity_camera); 
       mCamera.startPreview(); 
      } 
     }); 
    } 
    else { 
     tvCheck.setText("You did not select an image"); 
    } 
} 

/****************************************************************/ 

/** Stores jpeg picture */ 
PictureCallback jpegCallback = new PictureCallback() { 
    public void onPictureTaken(byte[] data, Camera camera) { 
     try { 
      File mediaStorageDir = new File(Environment        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCamera"); 
      // Saving image to the SD CARD with a file operation 
      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
      File mediaFile; 
      mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg"); 
      FileOutputStream outStream = new FileOutputStream(mediaFile); 
      outStream.write(data); 
      outStream.close(); 
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); 
      Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
     }  Log.d(TAG, "onPictureTaken - jpeg"); 
    } 
}; 


/***************************************************************/ 

/** Check if this device has a camera */ 
private boolean checkCameraHardware(Context context) { 
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){ 
     Log.d(TAG, "Camera Available"); 
     return true; 
    } else { 
     Log.d(TAG, "No Camera Found"); 
     return false; 
    } 
} 

/** A safe way to get an instance of the Camera object. */ 
public Camera getCameraInstance(){ 
    Camera c = null; 
    try { 
     int i = Camera.getNumberOfCameras(); 
     releaseCamera(); //in case camera is being accessed by any other app. 
     Log.d(TAG, "Number of Cameras "+i +"\n"); 
     c = Camera.open(); // attempt to get a Camera instance 
     Log.d(TAG, "Camera Opened"); 
    } 
    catch (Exception e){ 
     Log.d(TAG, "Camera Can't Be Accessed"); 
    } 
    return c; // returns null if camera is unavailable 
} 


@Override 
    protected void onPause() { 
     super.onPause(); 
     releaseCamera();    // release the camera immediately on pause event 
    } 

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

    @Override 
    public void onResume() { 
     super.onResume(); 
     // Get the Camera instance as the activity achieves full user focus 
     if (mCamera == null) { 
      getCameraInstance(); 
      mCamera.startPreview(); 
     } 
    } 

} 

這是我的攝像頭預覽類:

@SuppressLint({ "ViewConstructor", "SdCardPath" }) 
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { 
private static final String TAG = "CameraPreview"; 
private SurfaceHolder mHolder; 
private Camera mCamera; 
private Size mPreviewSize; 
// private Activity CameraActivity; 

@SuppressWarnings("deprecation") 
public CameraPreview(Context context, Camera camera, Activity activity) { 
    super(context); 
    mCamera = camera; 
    //CameraActivity = activity; 
    // Install a SurfaceHolder.Callback so we get notified when the 
    // underlying surface is created and destroyed. 
    mHolder = getHolder(); 
    mHolder.addCallback(this); 
    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); 
     //add camera preview call back here. 
     mCamera.startPreview(); 
    } catch (IOException e) { 
     Log.d(TAG, "Error setting camera preview: " + e.getMessage()); 
    } 
} 


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 
     } 


    // set preview size and make any resize, rotate or 
    // reformatting changes here 
    Camera.Parameters parameters = mCamera.getParameters(); 
    List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes(); 
    mPreviewSize = localSizes.get(0); 
    Log.d(TAG, "Width " + mPreviewSize.width); 
    Log.d(TAG, "Height " + mPreviewSize.height); 

    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height); 
    mHolder.setFixedSize(mPreviewSize.width, mPreviewSize.height); 
    requestLayout(); 
    mCamera.setParameters(parameters); 

    //start preview with new settings 
    try { 
      mCamera.setPreviewDisplay(mHolder); 
      mCamera.setDisplayOrientation(90); 
      //setCameraDisplayOrientation(CameraActivity, 0, mCamera); 
      mCamera.startPreview(); 
    } catch (Exception e){ 
     Log.d(TAG, "Error starting camera preview: " + e.getMessage()); 
    } 
} 
} 

回答

3

您創建一個CameraPreview唯一的onCreate()的活動。但是相機實例被釋放onPause(),並且一個新的onResume()被打開。因此,您需要再次設置曲面。

+0

我已經在onResume函數中添加了以下代碼..但它仍然不再顯示相機視圖。 mPreview = new CameraPreview(this,mCamera,CameraActivity.this); preview =(FrameLayout)findViewById(R.id.camera_preview); preview.addView(mPreview); – Haleema

+0

您的FrameView中可能已經有一個CameraPreview子元素(在'preview'字段中引用),並且在那裏有多個子元素並不好。 –

+0

調試完代碼後,我發現我在preview.addView(mPreview)上得到了一個nullpointerexception。我該怎麼辦? – Haleema

相關問題