1

I'm trying to get the audio volume on Android using JNI from C++. My constraint is that I don't have any access to the Java part.

I found a way to make my JNI query from this site: AudioManager.cpp

but I supposed I did something wrong with my last call in this code:

jclass AudioManager = env->FindClass("android/media/AudioManager");

jmethodID getStreamVolume = env->GetMethodID(AudioManager, "getStreamVolume", "()I");

jint stream = 3; //STREAM_MUSIC
int volume = env->CallIntMethod(AudioManager, getStreamVolume, stream); //Crash here

In this code, I'm trying to get the audio volume from STREAM_MUSIC identified by id=3 in the Android documentation: http://developer.android.com/reference/android/media/AudioManager.html#getStreamVolume(int)

EDIT: This is my working code:

jclass context = env->FindClass("android/content/Context");

jfieldID audioServiceField = env->GetStaticFieldID(context, "AUDIO_SERVICE", "Ljava/lang/String;");

jstring jstr = (jstring)env->GetStaticObjectField(context, audioServiceField);

jmethodID getSystemServiceID = env->GetMethodID(context, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");

jobject tm = env->CallObjectMethod(currentAndroidActivity, getSystemServiceID, jstr);

jclass AudioManager = env->FindClass("android/media/AudioManager");

jmethodID getStreamVolume = env->GetMethodID(AudioManager, "getStreamVolume", "(I)I");

jint stream = 3; //MUSIC_STREAM = 3
int volume = env->CallIntMethod(tm, getStreamVolume, stream);
DEBUG_LOG(DEBUG_TAG, "volume = " + to_string(volume));
2
  • 2
    You got a Class object -- not an instance of AudioManager -- and then tried to call an AudioManager method on it. You need an instance of AudioManager. Why don't you have access to any of the app's objects?
    – fadden
    Sep 25, 2015 at 16:07
  • I can get the current activity instance. Maybe I'll be able to get the AudioManager instance from that. I'm working on a plugin that will be hooked with some Android apps to get some data. That's why I can't manage that in the Java part. I don't want to force Android devs to modify their code for that. Sep 25, 2015 at 16:35

1 Answer 1

3

You need an instance of AudioManager to call that method. To get the instance, you can use context.getSystemService(Context.AUDIO_SERVICE) (as per documentation you linked to).

The AudioManager.cpp you linked to doesn't actually read the stream volume value, just the value of the static STREAM_MUSIC field and therefore doesn't need an instance of AudioManager.

The main problem in getting an instance of AudioManager here is really that to do that you need a Context instance, which is usually your Activity, Service or Application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.