Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...