安卓(Android) 怎么通过反射查找相机(Camera)ID

2019年10月26日20:48:16安卓(Android) 怎么通过反射查找相机(Camera)ID已关闭评论 429 1698字阅读5分39秒

1.简介

安卓(Android) 怎么通过反射查找相机(Camera)ID?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



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;
        }

        int level = android.os.Build.VERSION.SDK_INT;
        if (level >= 9) { 
            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 { 
            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 {
            
            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;
    }
}

 
继续阅读
编程十万个怎么办