因爲應用支持Android 2.2 版本,因此直接使用Camera.open()打開Camera,但據反應在某些平板上無後置攝像頭但有前置攝像頭的時候,則沒法使用(由於open()方法只能打開後置攝像頭)。 java
故使用反射則中解決,默認使用後置。(在臺電平板上已測試經過) android
/** * 打開默認相機 * 默認打開後置攝像頭,若沒有則打開前置 * @return */ public static Camera openDefaultCamera() { Camera camera = null; try { Class<?> cameraClass = Camera.class; Method method = cameraClass.getMethod("getNumberOfCameras"); int cameraNum = (Integer) method.invoke(null); int backId = -1; int frontId = -1; int defaultId = 0; Class<?>[] classes = cameraClass.getDeclaredClasses(); Class<?> cameraInfoCalss = null; for (Class<?> clz : classes) { String name = clz.getName(); if (name.equals("android.hardware.Camera$CameraInfo")) { cameraInfoCalss = clz; } } if (cameraInfoCalss == null) { return camera; } Field backField = cameraInfoCalss.getField("CAMERA_FACING_BACK"); Field frontField = cameraInfoCalss.getField("CAMERA_FACING_FRONT"); //獲取先後攝像頭默認facing int值 int backFacing = backField.getInt(cameraInfoCalss); int frontFacing = frontField.getInt(cameraInfoCalss); java.lang.reflect.Constructor cons = cameraInfoCalss.getConstructor(); if (cons == null) { return camera; } Object cameraInfo = cons.newInstance(); for (int i = 0; i < cameraNum; i++) { Method getCameraInfo = cameraClass.getMethod("getCameraInfo", int.class, cameraInfoCalss); getCameraInfo.invoke(null, i, cameraInfo); if (cameraInfo == null) { continue; } Field field = cameraInfoCalss.getDeclaredField("facing"); int facing = field.getInt(cameraInfo); if (facing == backFacing) { backId = defaultId; defaultId++; } else if (facing == frontFacing) { frontId = defaultId; defaultId++; } } Method openMethod = cameraClass.getMethod("open", int.class); if (backId != -1) { //默認使用後置攝像頭 camera = (Camera) openMethod.invoke(null, backId); } else if (frontId != -1) { camera = (Camera) openMethod.invoke(null, frontId); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } if (camera == null) { //若爲空,使用默認方法打開一次 camera = Camera.open(); } return camera; }