find Back Camera Id via reflection - Android Camera

Android examples for Camera:Back Camera

Description

find Back Camera Id via reflection

Demo Code


//package com.java2s;

import java.lang.reflect.Method;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;

import android.os.Build;

public class Main {
    public static final int CAMERA_FACING_BACK = 0;
    public static final int NO_CAMERA = -1;

    @SuppressLint("NewApi")
    public static int findBackCameraId(Context context) {
        int result = NO_CAMERA;
        //??????????????????
        if (!isSupportBackCamera(context)) {
            return result;
        }//from w w  w .  j  ava  2s.  co  m

        int level = android.os.Build.VERSION.SDK_INT;
        if (level >= 9) { //2.3???
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            int cameraCount = Camera.getNumberOfCameras();
            for (int i = 0; i < cameraCount; i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    result = i;
                    break;
                }
            }
        } else { //2.3???? 
            result = 0;
        }

        return result;
    }

    public static boolean isSupportBackCamera(Context context) {
        PackageManager pm = context.getPackageManager();
        return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

    @SuppressLint("NewApi")
    public static Object getCameraInfo(int cameraId) {
        Object result = null;
        if (Build.VERSION.SDK_INT >= 9) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(cameraId, info);
            result = info;
        } else {
            //????CameraInfo???????
            Class<?> cameraClass;
            try {
                cameraClass = Class.forName("android.hardware.Camera");
                Object cameraInfo = null;
                Class<?> cameraInfoClass = Class
                        .forName("android.hardware.Camera$CameraInfo");
                if (cameraInfoClass != null) {
                    cameraInfo = cameraInfoClass.newInstance();
                }
                Method getCameraInfoMethod = cameraClass.getMethod(
                        "getCameraInfo", Integer.TYPE, cameraInfoClass);
                if (getCameraInfoMethod != null && cameraInfoClass != null) {
                    getCameraInfoMethod.invoke(null, cameraId, cameraInfo);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}

Related Tutorials