Constantly check for volume change in Android services

前端 未结 1 2035
情话喂你
情话喂你 2020-12-16 22:56

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 s

相关标签:
1条回答
  • 2020-12-16 23:14

    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);
    
    0 讨论(0)
提交回复
热议问题