Issue
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));
Solution
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
.
Answered By - Zharf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.