Constantly check for volume change in Android serv

2019-01-24 11:14发布

问题:

I wrote this piece of code, it's obviously flawed. How do I go about creating a service which will constantly check for changes in volume? Key listeners cannot be used in services, please don't post an answer with volume key listeners.

My code is wrong because I've given dummy condition for the while loop. What has to be the condition for my service to check for volume change and not crash? It can't be isScreenOn() because volume can be changed while listening to music and the screen is off.

CODE

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);
    int newVolume=0;
    while(1==1)
    {
        newVolume = audio.getStreamVolume(AudioManager.STREAM_RING);
        if(currentVolume!=newVolume)
        {
            Toast.makeText(this, "Volume change detected!", Toast.LENGTH_LONG).show();
        }

    }

回答1:

If you want to see when the setting changes, you can register a ContentObserver with the settings provider to monitor it. For example, this is the observer in the settings app:

    private ContentObserver mVolumeObserver = new ContentObserver(mHandler) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            if (mSeekBar != null && mAudioManager != null) {
                int volume = mAudioManager.getStreamVolume(mStreamType);
                mSeekBar.setProgress(volume);
            }
        }
    };

And it is registered to observer the settings like this:

        import android.provider.Settings;
        import android.provider.Settings.System;

        mContext.getContentResolver().registerContentObserver(
                System.getUriFor(System.VOLUME_SETTINGS[mStreamType]),
                false, mVolumeObserver);