It's a legacy method that has been around for a long time, but I'll write it because the information that comes out by google is a little impractical.
There is AudioManager.VOLUME_CHANGED_ACTION (android.media.VOLUME_CHANGED_ACTION) as an Intent that detects when the volume is changed or the volume button is pressed. All you have to do is receive this with the Broadcast Receiver.
Up to this point, the information that comes out immediately after google, but AudioManager.VOLUME_CHANGED_ACTION needs to be aware of the following points.
--Multiple events are notified by one volume change operation --AudioManager.STREAM_MUSIC, etc. Notified for each STREAM, and even if the volume does not change --The volume UI is displayed when the first button is operated while the screen is ON, and the event is not notified because the volume does not actually change. --When the screen is off, the event will not be notified even if you press the button unless you are playing music with a music app, etc. --Because the volume does not change
AndroidManifest.xml
<receiver android:name=".VolumeChangedActionReceiver">
<intent-filter>
<actionandroid:name="android.media.VOLUME_CHANGED_ACTION" />
</intent-filter>
</receiver>
VolumeChangedActionReceiver.java
public static class VolumeChangedActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
int newVolume = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_VALUE", 0);
int oldVolume = intent.getIntExtra("android.media.EXTRA_PREV_VOLUME_STREAM_VALUE", 0);
int streamType = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_TYPE", 0);
if (streamType == AudioManager.STREAM_MUSIC) {
// TODO: write your code
}
}
}
}
Recommended Posts