Skip to main content

Calling Android camera functions in Unity

init-qyUnityunityC#Less than 1 minute

Unity itself provides interfaces such as WebcamDevice and WebcamTexture to support access to physical cameras. However, these interfaces provide limited parameters, so we need to call native functions in Unity to obtain the corresponding parameters.

Environment

Since Android or Unity versions change rapidly, here is the current environment:

  • Unity 2021.3.19f1
  • Android 12.0 API31 emulator

Usage

The following code is an example of using the CameraCharacteristics class in Android to obtain the available focal_length and sensor_info_physical_size.

var player = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
var activity = player.GetStatic<AndroidJavaObject>("currentActivity");
var cameraManager = activity.Call<AndroidJavaObject>("getSystemService", "camera");
if (cameraManager != null)
{
    var CameraCharacteristics = cameraManager.Call<AndroidJavaObject>("getCameraCharacteristics", "0"); // device id

    AndroidJavaObject key_focal_lens = CameraCharacteristics.GetStatic<AndroidJavaObject>("LENS_INFO_AVAILABLE_FOCAL_LENGTHS");
    AndroidJavaObject key_sensor_size = CameraCharacteristics.GetStatic<AndroidJavaObject>("SENSOR_INFO_PHYSICAL_SIZE");
    float[] focal_lens = CameraCharacteristics.Call<float[]>("get", key_focal_lens);
    AndroidJavaObject sensor_size = CameraCharacteristics.Call<AndroidJavaObject>("get", key_sensor_size);
    float sensor_width = sensor_size.Call<float>("getWidth");
}

In the code above, if you are calling a method in a class, use Call, where the first parameter is the method name and the second parameter is optional, representing the arguments passed.
If the original class is needed during the argument passing process, such as the Key in the code above, it needs to be wrapped with AndroidJavaObject. Only some basic types (int, float[]) can be passed directly.
If you are accessing a member (fields) in a class, use GetStatic. For example, CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS in Java can be obtained using GetStatic.

References

This post is translated using ChatGPT, please feedbackopen in new window if any omissions.