1
0
mirror of https://codeberg.org/Freeyourgadget/Gadgetbridge synced 2024-12-24 17:45:50 +01:00

Debounce onSetMusicInfo/onSetMusicState calls

When music player switchs a song, multiple notifications(around 5 in my
test) are sent to NotificationListner, during this,
MediaControllerCompat does not always get the music info we need, the
music info and state seem randomly combined previous song and current
one.

To avoid unnecessary music info updates, debounce
onSetMusicInfo/onSetMusicState calls, so only the last music info and
state are sent to the device.
This commit is contained in:
Zhong Jianxin 2020-05-19 22:53:19 +08:00
parent 8d145917f5
commit 6335b4c86a

View File

@ -33,6 +33,7 @@ import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadata;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.RemoteException;
import android.service.notification.NotificationListenerService;
@ -118,6 +119,10 @@ public class NotificationListener extends NotificationListenerService {
private long activeCallPostTime;
private int mLastCallCommand = CallSpec.CALL_UNDEFINED;
private Handler mHandler = new Handler();
private Runnable mSetMusicInfoRunnable = null;
private Runnable mSetMusicStateRunnable = null;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
@ -618,8 +623,8 @@ public class NotificationListener extends NotificationListenerService {
* @return true if notification was handled, false otherwise
*/
public boolean handleMediaSessionNotification(MediaSessionCompat.Token mediaSession) {
MusicSpec musicSpec = new MusicSpec();
MusicStateSpec stateSpec = new MusicStateSpec();
final MusicSpec musicSpec = new MusicSpec();
final MusicStateSpec stateSpec = new MusicStateSpec();
MediaControllerCompat c;
try {
@ -662,8 +667,27 @@ public class NotificationListener extends NotificationListenerService {
musicSpec.trackNr = (int) d.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER);
// finally, tell the device about it
GBApplication.deviceService().onSetMusicInfo(musicSpec);
GBApplication.deviceService().onSetMusicState(stateSpec);
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 e) {