安卓(Android) 怎么通过反射获取相机(Camera)方向

2019年10月27日22:27:48安卓(Android) 怎么通过反射获取相机(Camera)方向已关闭评论 383 1495字阅读4分59秒

1.简介

安卓(Android) 怎么通过反射获取相机(Camera)方向?——请看下文。

2.示例代码

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



import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.annotation.SuppressLint;

import android.hardware.Camera;

import android.os.Build;

public class Main {

    @SuppressLint("NewApi")
    public static int getCameraOrientation(int cameraId) {
        int result = 90;
        Object info = getCameraInfo(cameraId);
        if (info != null) {
            if (Build.VERSION.SDK_INT >= 9) {
                result = ((Camera.CameraInfo) info).orientation;
            } else {
                Object r = getCameraInfoField(info, "orientation");
                if (r != null) {
                    result = (Integer) r;
                }
            }
        }
        return result;
    }

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

    protected static Object getCameraInfoField(Object info, String fieldKey) {
        Object result = null;
        try {
            Field field = info.getClass().getField("orientation");
            result = field.getInt(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

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