Is there any way to listen to the event of volume change on Android, without just taking over the volume buttons?
The only thing I\'ve found that works is here, but
Better, you can register a ContentObserver
as follows:
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, new ContentObserver(){...} );
Your ContentObserver might look like this:
public class SettingsContentObserver extends ContentObserver {
private AudioManager audioManager;
public SettingsContentObserver(Context context, Handler handler) {
super(handler);
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
@Override
public boolean deliverSelfNotifications() {
return false;
}
@Override
public void onChange(boolean selfChange) {
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.d(TAG, "Volume now " + currentVolume);
}
}
When done:
getApplicationContext().getContentResolver().unregisterContentObserver(mContentObserver);
One caution, though - sometimes the notifications seem to be delayed if there are lots of button presses quickly.
You can use : registerMediaButtonEventReceiver (ComponentName eventReceiver) which registers a component to be the sole receiver of MEDIA_BUTTON intents.
// in your activity.
MediaButtonReceiver receiver = new MediaButtonReceiver();
// in onCreate put
registerMediaButtonEventReceiver(receiver);
class MediaButtonReceiver implements BroadcastReceiver {
void onReceive(Intent intent) {
KeyEvent ke = (KeyEvent)intent.getExtra(Intent.EXTRA_KEY_EVENT);
if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
//action when volume goes down
}
if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
//action when volume goes up
}
}
}
//In both onStop and onPause put :
unregisterMediaButtonEventReceiver(receiver);
what we are doing here is defining a BroadcastReceiver that deals with ACTION_MEDIA_BUTTON. and use EXTRA_KEY_EVENT which is containing the key event that caused the broadcast to get what was pressed and act upon that.
Use broadcast receiver VOLUME_CHANGED_ACTION then use AudioManager to obtain current volume.
<receiver android:name="VolumeChangeReceiver" >
<intent-filter>
<action android:name="android.media.VOLUME_CHANGED_ACTION" />
</intent-filter>
</receiver>
ok , for now , what i do is to listen to the volume buttons using onKeyDown (and check for KEYCODE_VOLUME_DOWN,KEYCODE_VOLUME_MUTE,KEYCODE_VOLUME_UP ) , and using a handler i've posted a new runnable that checks the volume level .
also , since some devices have a volume dialog , i've added a listener to when it is being disappeared , according to this link.