use of android.support.v4.media.session.PlaybackStateCompat in project Gadgetbridge by Freeyourgadget.
the class NotificationListener method handleMediaSessionNotification.
/**
* Try to handle media session notifications that tell info about the current play state.
*
* @param mediaSession The mediasession to handle.
* @return true if notification was handled, false otherwise
*/
public boolean handleMediaSessionNotification(MediaSessionCompat.Token mediaSession) {
final MusicSpec musicSpec = new MusicSpec();
final MusicStateSpec stateSpec = new MusicStateSpec();
MediaControllerCompat c;
try {
c = new MediaControllerCompat(getApplicationContext(), mediaSession);
PlaybackStateCompat s = c.getPlaybackState();
stateSpec.position = (int) (s.getPosition() / 1000);
stateSpec.playRate = Math.round(100 * s.getPlaybackSpeed());
stateSpec.repeat = 1;
stateSpec.shuffle = 1;
switch(s.getState()) {
case PlaybackStateCompat.STATE_PLAYING:
stateSpec.state = MusicStateSpec.STATE_PLAYING;
break;
case PlaybackStateCompat.STATE_STOPPED:
stateSpec.state = MusicStateSpec.STATE_STOPPED;
break;
case PlaybackStateCompat.STATE_PAUSED:
stateSpec.state = MusicStateSpec.STATE_PAUSED;
break;
default:
stateSpec.state = MusicStateSpec.STATE_UNKNOWN;
break;
}
MediaMetadataCompat d = c.getMetadata();
if (d == null)
return false;
if (d.containsKey(MediaMetadata.METADATA_KEY_ARTIST))
musicSpec.artist = d.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
if (d.containsKey(MediaMetadata.METADATA_KEY_ALBUM))
musicSpec.album = d.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
if (d.containsKey(MediaMetadata.METADATA_KEY_TITLE))
musicSpec.track = d.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
if (d.containsKey(MediaMetadata.METADATA_KEY_DURATION))
musicSpec.duration = (int) d.getLong(MediaMetadataCompat.METADATA_KEY_DURATION) / 1000;
if (d.containsKey(MediaMetadata.METADATA_KEY_NUM_TRACKS))
musicSpec.trackCount = (int) d.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS);
if (d.containsKey(MediaMetadata.METADATA_KEY_TRACK_NUMBER))
musicSpec.trackNr = (int) d.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER);
// finally, tell the device about it
if (mSetMusicInfoRunnable != null) {
mHandler.removeCallbacks(mSetMusicInfoRunnable);
}
mSetMusicInfoRunnable = new Runnable() {
@Override
public void run() {
GBApplication.deviceService().onSetMusicInfo(musicSpec);
}
};
mHandler.postDelayed(mSetMusicInfoRunnable, 100);
if (mSetMusicStateRunnable != null) {
mHandler.removeCallbacks(mSetMusicStateRunnable);
}
mSetMusicStateRunnable = new Runnable() {
@Override
public void run() {
GBApplication.deviceService().onSetMusicState(stateSpec);
}
};
mHandler.postDelayed(mSetMusicStateRunnable, 100);
return true;
} catch (NullPointerException | RemoteException | SecurityException e) {
return false;
}
}
Aggregations