This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

background

Building on the previous two articles, this article will show you how to get system Services and call some of the system-provided methods. Because each of these methods requires a context object, we need to know how to get that context object.

case

The following uses setting and obtaining the system volume as an example:

1.androidActivity()Method returns a handle to the application’s main Activity, which is the context we need.

Android Services are defined in the Context package and are statically defined names, as follows:

So if you want to call getSystemService, the first thing you need to do is get its argument, which is the audio string, which you get from the getStaticObjectField method, and the purpose of this method is to get the global static variable, and once you get the global variable, Call the getSystemService method and pass it in, and we get the AUDIO_SERVICE that we want.

OK, we have AUDIO_SERVICE, and since the return type is a base type, not an object, we can get the volume directly by calling the callMethod method

	QAndroidJniObject activity = androidActivity(a); QAndroidJniObject name = QAndroidJniObject::getStaticObjectField("android/content/Context"."AUDIO_SERVICE"."Ljava/lang/String;");
    QAndroidJniObject service = activity.callObjectMethod("getSystemService"."(Ljava/lang/String;) Ljava/lang/Object;",name.object<jstring>());
    //STREAM_MUSIC ==3 FLAG_PLAY_SOUND == 4
    const int maxVolume = service.callMethod<jint>("getStreamVolume"."(I)I".3);
Copy the code

Of course, we have AUDIO_SERVICE, which we can also use to set the volume:

service.callMethod<void> ("setStreamVolume"."(III)V".3,vol,4);
Copy the code

The Android prototype for setting the volume is:

audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, AudioManager.FLAG_PLAY_SOUND);
Copy the code