Unity – Get current android volume with JNI without native plugin

Désolé, cet article est seulement disponible en English.

To get the current volume value on Android in Unity without plugin you can use this c# script.
Thanks to the Java Native Interface.

You will get an integer between 0 and ?, 15, 13, 25, …
NB: Actually the max volume value depends of the OS version.

public int GetVolume ()
{
	AndroidJavaObject currentActivity = unityPlayerClass.GetStatic ( "currentActivity" );
	AndroidJavaObject packageManager = currentActivity.Call ( "getPackageManager" );
	AndroidJavaObject context = currentActivity.Call ( "getApplicationContext" );
	AndroidJavaClass audioManagerClass = new AndroidJavaClass ( "android.media.AudioManager" );
	AndroidJavaClass contextClass = new AndroidJavaClass ( "android.content.Context" );
	int AudioManager_STREAM_MUSIC = audioManagerClass.GetStatic<int> ( "STREAM_MUSIC" );
	string Context_AUDIO_SERVICE = contextClass.GetStatic<string> ( "AUDIO_SERVICE" );
	AndroidJavaObject audioService = context.Call<AndroidJavaObject> ( "getSystemService", Context_AUDIO_SERVICE );
	return audioService.Call<int> ( "getStreamVolume", AudioManager_STREAM_MUSIC );
}