一尘不染

音量总是一样吗?

algorithm

我有以下代码,我想在按住音量按钮和当前音量之前获得上一音量的差值。但是,当我调试时,我发现以前的卷和当前的卷总是相同的:

在此处输入图片说明

这是我的代码:

package curlybrace.ruchir.ivebeenstuckfortwodays;

import android.content.Context;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.os.Handler;


/**
 * Created by ruchir on 2/5/2016.
 */
public class volumeCheck extends ContentObserver {
    int previousVolume;
    Context context;

    public volumeCheck(Context c, Handler handler) {
        super(handler); //Creates a new handler
        context=c; //variable context, defined earlier, is set equal to c, context of service.

        AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); //retrieve an AudioManager for handling management of volume, ringer modes and audio routing.
        previousVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC); //The volume that we get before the `onChange` is called
    }

    @Override
    public boolean deliverSelfNotifications() {
        return super.deliverSelfNotifications();
    }

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

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

        processVolumeChange(previousVolume, currentVolume);
    }

    public void processVolumeChange(int previousVolume, int currentVolume) {

        MyService mService = new MyService();
        mService.volumeCheck(previousVolume - currentVolume); //Method in my service


    }
}

我已经尝试了两天,但我不知道为什么值相同。请帮忙。

编辑:

我的服务中包含以下代码onCreate

     mSettingsContentObserver = new volumeCheck(this, new Handler());
   getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);

谢谢


阅读 240

收藏
2020-07-28

共1个答案

一尘不染

您可能没有更改设备上的媒体音量。要进行验证,请转到“设置”->“声音和通知”,然后尝试更改在那里找到的媒体音量。

在此处输入图片说明

您可能也想previousVolume在更改后也更新更新:

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

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

    processVolumeChange(currentVolume);
}

public void processVolumeChange(int currentVolume) {
    MyService mService = new MyService();
    mService.volumeCheck(previousVolume - currentVolume); //Method in my service
    previousVolume = currentVolume;
}
2020-07-28