How to register ContentObserver for media volume change?

邮差的信 提交于 2019-12-04 14:08:10

Change your onChange meathod to the following

@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);

    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);

    int delta=previousVolume-currentVolume;

    if(delta>0)
    {
        Logger.d("Decreased");
        previousVolume=currentVolume;
    }
    else if(delta<0)
    {
        Logger.d("Increased");
        previousVolume=currentVolume;
    }
}

You can monitor for changes to a specific stream by using a more specific URI than Settings.System.CONTENT_URI. The method Settings.System.getUriFor() will return the URI for a specific stream.

For example:

Uri uri = Settings.System.getUriFor(Settings.System.VOLUME_SETTINGS[AudioManager.STREAM_RING]);
appContext.getContentResolver().registerContentObserver(uri, true, myObserver);

Andy Dennie:

I have just tested approach suggested by you:

Uri uri = Settings.System .getUriFor(Settings.System.VOLUME_SETTINGS[AudioManager.STREAM_MUSIC]); appContext.getContentResolver().registerContentObserver(uri, true, myObserver);

and if I register for this URI, volume changes on STREAM_MUSIC aren't detected. But If I use

android.provider.Settings.System.CONTENT_URI

it works perfectly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!