Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

audio - Constantly check for volume change in Android services

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();
        }

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...