音量总是一样的吗?

时间:2016-02-07 17:02:48

标签: java android string algorithm function

我有以下代码,我希望在按住音量按钮和当前音量之前获得前一音量的差异。但是,当我调试时,我发现前一卷和当前卷总是一样的:

enter image description here

这是我的代码:

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

由于

1 个答案:

答案 0 :(得分:1)

您可能无法更改设备上的媒体音量。要验证转到设置 - >声音&通知并尝试更改在那里找到的媒体量。

enter image description here

您可能还希望在更改后更新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;
}