关于安卓摄像头前后切换的问题

qq_27088765 2015-10-24 12:31:38
我设置了一个按钮切换

bt_change = (Button) findViewById(R.id.button_change);
bt_change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

mCamera.stopPreview();
mCamera.release();
mCamera =null;
mCamera = Camera.open(1);
mPreview.setCamera(mCamera);
mCamera.startPreview();


}
});

}

这条写的,我是把预览图放在FrameLayout的,点击切换按钮以后,相机预览就定格在一个画面不动了,这个画面是后置摄像头的,但是我再按拍照,拍出来的是前置摄像头的照片,只不过我看不见预览图,拍照结束后能看见
...全文
367 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_27088765 2015-10-24
  • 打赏
  • 举报
回复
Activity package com.example.shanamaid.myapplication; /** * Created by ShanaMaid on 2015/10/21. */ import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ConcurrentMap; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.PictureCallback; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.Display; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.Toast; public class HelloCustomCameraActivity extends Activity { private Camera mCamera; private CameraPreview mPreview; public int flag=1;//拍照结束判定 int mNumberOfCameras; int mCameraCurrentlyLocked; private Camera.AutoFocusCallback mAutoFocusCallback; private Button bt_change;//切换摄像头 private FrameLayout preview; private FrameLayout preview1; // The first rear facing camera int mDefaultCameraId; int mScreenWidth, mScreenHeight; @Override public void onCreate(Bundle savedInstanceState) { Log.d("AppConstants.LOG_TAG", "onCreate"); super.onCreate(savedInstanceState); // 无标题栏的窗口 requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // 设置布局 setContentView(R.layout.activity_hello_custom_camera); // 得到屏幕的大小 WindowManager wManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wManager.getDefaultDisplay(); mScreenHeight = display.getHeight(); mScreenWidth = display.getWidth(); // mAutoFocusCallback = new Camera.AutoFocusCallback() { // // public void onAutoFocus(boolean success, Camera camera) { // // TODO Auto-generated method stub // if(success){ // mCamera.setOneShotPreviewCallback(null); // // } // // // } // };//自动聚焦 // Create our Preview view and set it as the content of our activity. // mPreview = new CameraPreview(this); preview = (FrameLayout) findViewById(R.id.camera_preview); preview1 = (FrameLayout) findViewById(R.id.camera_preview_1); mPreview = new CameraPreview(this); // 将相机预览图加入帧布局里面 preview.addView(mPreview, 0); // 使用按钮进行拍摄动作监听 Button captureButton = (Button) findViewById(R.id.button_capture); captureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // get an image from the camera if(flag==1) { flag=0; mCamera.takePicture(null, null, mPicture); } } }); // 得到默认的相机ID mDefaultCameraId = getDefaultCameraId(); mCameraCurrentlyLocked = mDefaultCameraId; bt_change = (Button) findViewById(R.id.button_change); bt_change.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCamera.stopPreview(); mCamera.release(); mCamera =null; mCamera = Camera.open(1); mPreview.setCamera(mCamera); mCamera.startPreview(); } }); } @Override protected void onResume() { Log.d("AppConstants.LOG_TAG", "onResume"); super.onResume(); // Open the default i.e. the first rear facing camera. mCamera = getCameraInstance(mCameraCurrentlyLocked); // if(a==0){ // mCamera = getCameraInstance(0); // mPreview.setCamera(mCamera); // } // else{ // mCamera = getCameraInstance(1); mPreview.setCamera(mCamera); // } } @Override protected void onPause() { Log.d("AppConstants.LOG_TAG", "onPause"); super.onPause(); // Because the Camera object is a shared resource, it's very // important to release it when the activity is paused. if (mCamera != null) { mPreview.setCamera(null); Log.d("AppConstants.LOG_TAG", "onPause --> Realease camera"); mCamera.release(); mCamera = null; } } @Override protected void onDestroy() { Log.d("AppConstants.LOG_TAG", "onDestroy"); super.onDestroy(); } /** * 得到默认相机的ID * * @return */ private int getDefaultCameraId() { Log.d("AppConstants.LOG_TAG", "getDefaultCameraId"); int defaultId = -1; // Find the total number of cameras available mNumberOfCameras = Camera.getNumberOfCameras(); // Find the ID of the default camera CameraInfo cameraInfo = new CameraInfo(); for (int i = 0; i < mNumberOfCameras; i++) { Camera.getCameraInfo(i, cameraInfo); Log.d("AppConstants.LOG_TAG", "camera info: " + cameraInfo.orientation); if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { defaultId = i; } } if (-1 == defaultId) { if (mNumberOfCameras > 0) { // 如果没有后向摄像头 defaultId = 0; } else { // 没有摄像头 Toast.makeText(getApplicationContext(), R.string.no_camera, Toast.LENGTH_LONG).show(); } } return defaultId; } /** A safe way to get an instance of the Camera object. */ public static Camera getCameraInstance(int cameraId) { Log.d("AppConstants.LOG_TAG", "getCameraInstance"); Camera c = null; try { c = Camera.open(cameraId); // attempt to get a Camera instance } catch (Exception e) { // Camera is not available (in use or does not exist) e.printStackTrace(); Log.e("AppConstants.LOG_TAG", "Camera is not available"); } return c; // returns null if camera is unavailable } public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; /** Create a File for saving an image or video */ private static File getOutputMediaFile(int type) { Log.d("AppConstants.LOG_TAG", "getOutputMediaFile"); // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = null; try { // This location works best if you want the created images to be // shared // between applications and persist after your app has been // uninstalled. mediaStorageDir = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), ""); } catch (Exception e) { e.printStackTrace(); } // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { // 在SD卡上创建文件夹需要权限: // <uses-permission // android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") .format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; } private PictureCallback mPicture = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null) { return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } // 拍照后重新开始预览 mCamera.stopPreview(); mCamera.startPreview(); flag=1; } }; /** Check if this device has a camera */ private 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; } } }
qq_27088765 2015-10-24
  • 打赏
  • 举报
回复
package com.example.shanamaid.myapplication; import java.io.IOException; import java.util.List; import android.R.integer; import android.content.Context; import android.graphics.ImageFormat; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Size; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * 相机图片预览类 * * @author * */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private Camera mCamera; Size mPreviewSize; List<Size> mSupportedPreviewSizes; public CameraPreview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public CameraPreview(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CameraPreview(Context context) { super(context); init(); } /** * 初始化工作 * */ private void init() { Log.d("AppConstants.LOG_TAG", "CameraPreview initialize"); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void setCamera(Camera camera) { mCamera = camera; if (mCamera != null) { mSupportedPreviewSizes = mCamera.getParameters() .getSupportedPreviewSizes(); requestLayout(); } } @Override public void surfaceCreated(SurfaceHolder holder) { Log.d("AppConstants.LOG_TAG", "surfaceCreated"); // The Surface has been created, now tell the camera where to draw the // preview. try { if (null != mCamera) { mCamera.setPreviewDisplay(holder); } } catch (IOException e1) { e1.printStackTrace(); Log.d("AppConstants.LOG_TAG", "Error setting camera preview display: " + e1.getMessage()); } try { if (null != mCamera) { mCamera.startPreview(); } Log.d("AppConstants.LOG_TAG", "surfaceCreated successfully! "); } catch (Exception e) { Log.d("AppConstants.LOG_TAG", "Error setting camera preview: " + e.getMessage()); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d("AppConstants.LOG_TAG", "surface changed"); // 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 (null == mHolder.getSurface()) { // preview surface does not exist return; } // stop preview before making changes try { if (null != mCamera) { 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 if (null != mCamera) { Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height); requestLayout(); mCamera.setParameters(parameters); mCamera.setDisplayOrientation(90); Log.d("AppConstants.LOG_TAG", "camera set parameters successfully!: " + parameters); } // 这里可以用来设置尺寸 // start preview with new settings try { if (null != mCamera) { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } } catch (Exception e) { Log.d("AppConstants.LOG_TAG", "Error starting camera preview: " + e.getMessage()); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d("AppConstants.LOG_TAG", "surfaceDestroyed"); if (null != mCamera) { mCamera.stopPreview(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // We purposely disregard child measurements because act as a // wrapper to a SurfaceView that centers the camera preview instead // of stretching it. final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height); if (mSupportedPreviewSizes != null) { mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height); } } private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.1; double targetRatio = (double) w / h; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio, ignore the requirement if (optimalSize == null) { minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; } } CameraPreview 类

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧