系统设置界面中就是使用AudioManager.setStreamVolume(),
说下比较难理解的flag参数在AudioManager在handlerKeyDown()中设置了两个flags,分别是FLAG_SHOW_UI和FLAG_VIBRATE.从字面上可知,前者告诉AudioService需要弹出一个音量控制面板,后者可能,只是可能是设置在为0时震动一下.而设置了FLAG_PLAY_SOUND是松开音量键时有个提示音.
源码:
/**
* Sets the volume index for a particular stream.
* <p>This method has no effect if the device implements a fixed volume policy
* as indicated by {@link #isVolumeFixed()}.
* <p>From N onward, volume adjustments that would toggle Do Not Disturb are not allowed unless
* the app has been granted Do Not Disturb Access.
* See {@link NotificationManager#isNotificationPolicyAccessGranted()}.
* @param streamType The stream whose volume index should be set.
* @param index The volume index to set. See
* {@link #getStreamMaxVolume(int)} for the largest valid value.
* @param flags One or more flags.
* @see #getStreamMaxVolume(int)