Skip to content

Instantly share code, notes, and snippets.

@derFunk
Created August 3, 2012 08:49
Show Gist options
  • Save derFunk/3246036 to your computer and use it in GitHub Desktop.
Save derFunk/3246036 to your computer and use it in GitHub Desktop.
Android device info bridge for Unity 3D
package de.chimeraentertainment.tools;
import android.content.Context;
import android.view.WindowManager;
import de.chimeraentertainment.namespace.<<YourMainActivity>>;
import android.util.DisplayMetrics;
import android.util.Log;
public class DeviceInfo {
/**
* Returns the rotation of the screen from its "natural" orientation
* @return Surface.ROTATION_X enum
*/
public static int getScreenRotation()
{
// you should cache that return value in your unity script.
return ((WindowManager)<<YourMainActivity>>.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
}
/**
* Get Screensize in inches
* @return 0 if error, screensize in inch if no error
*/
public static double getScreenSizeInInch()
{
// Compute screen size
try {
DisplayMetrics dm = <<YourMainActivity>>.getContext().getResources().getDisplayMetrics();
float screenWidth = dm.widthPixels / dm.xdpi;
float screenHeight = dm.heightPixels / dm.ydpi;
double size = Math.sqrt(Math.pow(screenWidth, 2) + Math.pow(screenHeight, 2));
return size;
} catch(Throwable t) {
Log.e("DeviceInfo", "Failed to compute screen size", t);
return 0;
}
}
}
using System;
using UnityEngine;
public class DeviceInfoAndroidImpl /* : IDeviceInfo // use an interface to implement it for ios as well */
{
private const int IsTabletAboveInch = 4;
private double screenSizeInch = -1;
private bool _IsTabletSize()
{
return screenSizeInch >= IsTabletAboveInch;
}
public int GetScreenRotation()
{
#if UNITY_ANDROID
int screenRot;
Debug.Log("Calling IsTabletSize() on Java...");
try
{
using (var javaDeviceInfo = new AndroidJavaClass("de.chimeraentertainment.tools.DeviceInfo"))
{
screenRot = javaDeviceInfo.CallStatic<int>("getScreenRotation");
}
}
catch (Exception e)
{
Debug.LogError(e);
return -1;
}
return screenRot;
#else
return 0;
#endif
}
public bool IsTabletSize()
{
#if UNITY_ANDROID
// cache value, don't make too many jni calls!
if (screenSizeInch > 0)
return _IsTabletSize();
Debug.Log("Calling IsTabletSize() on Java...");
try
{
using (var javaDeviceInfo = new AndroidJavaClass("de.chimeraentertainment.tools.DeviceInfo"))
{
screenSizeInch = javaDeviceInfo.CallStatic<double>("getScreenSizeInInch");
}
}
catch (Exception e)
{
Debug.LogError(e);
return false;
}
return _IsTabletSize();
#else
return false;
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment