Question

i am developing an android app, where my class extends ContentObserver.I am registering my class for observing the changes in VOLUME_RING.

the onchange method of my class gets called only upon volume button changes.

The problem is, an global int variable which is getting updated in the constructor of the class is not getting updates in onchange method.

The code below is what i have tried,

   public class VolumeChecker extends ContentObserver 
    {
         Context context;
         Handler handler;

         int initialVolume;


public VolumeChecker(Context c, Handler handler)
{
    super(handler);
    context=c;
    this.handler = handler;

    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    initialVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

    Log.e("inisde","volvhevker - intitvol " + initialVolume);

}

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

@Override
public void onChange(boolean selfChange) 
{

    super.onChange(selfChange);

    Log.e("onchange","initialVolume" + initialVolume);
    refresh();
}


public void refresh()
{
    new VolumeChecker(context,handler);
}

}

The initialVolume variable value, which is getting updated in the constructor upon refresh, is not getting reflected in the onchange method.

Please help.thanks!

Was it helpful?

Solution

What is the purpose of creating a new VolumeChecker within refresh()? You can simply update the variable again like so:

public void refresh() {
    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    initialVolume = audio.getStreamVolume(AudioManager.STREAM_RING);
}

and perhaps do some refactoring to make audio a global variable so that you do not have to recreate it each time. You can likely refactor the contents of the refresh() method directly into the onChange() method as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top