I want to detect the volume button click event in the background service or in native environment in Android.I hope it can detect the event at anytime.
I tried the code below with ContentObserver
, but this can detect only event of AUDIO_SERVICE
changing, if the foreground application is running with music, this method can not detect it, I think because it's STREAM_MUSIC
but not AUDIO_SERVICE
.What I want is detecting the volume button click at anytime and any volume button click.
Does anyone know how to do it? Can I implement it with C in native code?
public class SettingsContentObserver extends ContentObserver {
int previousVolume;
Context context;
public SettingsContentObserver(Context c, Handler handler) {
super(handler);
context=c;
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
previousVolume = audio.getStreamVolume(AudioManager.AUDIO_SERVICE);
}
@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.AUDIO_SERVICE);
int delta=previousVolume-currentVolume;
if(delta>0)
{
Logger.d("Volume Up!");
previousVolume=currentVolume;
}
else if(delta<0)
{
Logger.d("Volume Down!");
previousVolume=currentVolume;
}
}
}
Then in my service onCreate register it with:
mSettingsContentObserver = new SettingsContentObserver(this,new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver );
Then unregister in onDestroy:
getApplicationContext().getContentResolver().unregisterContentObserver(mSettingsContentObserver);