get Camera Orientation via reflection - Android Camera

Android examples for Camera:Camera Orientation

Description

get Camera Orientation via reflection

Demo Code


//package com.java2s;

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;
                }/*  www . j av a 2  s  .c  o m*/
            }
        }
        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;
    }
}

Related Tutorials