Saturday, 9 January 2021

Service time measurement

I have a service, that uses MediaSession for playing streams. I want to collect the time, how much this service plays music and then send it to the server. I use following code (simplified):

public class MyService extends MediaBrowserServiceCompat {

  private Long startTime;

  public class MediaPlayerListener extends PlaybackInfoListener {

    @Override
    public void onPlaybackStateChange(PlaybackStateCompat state) {
       session.setPlaybackState(state);

       switch (state.getState()) {
           case PlaybackStateCompat.STATE_PLAYING:
               startTime = SystemClock.elapsedRealtime();
               startForeground(MediaNotificationManager.NOTIFICATION_ID, notification);
               break;
           case PlaybackStateCompat.STATE_STOPPED:
               long timediff = SystemClock.elapsedRealtime() - startTime;
               stopForeground(true);
               stopSelf();
               // timediff is being sent to the server here 
               break;
       }
   }
}

The service works as expected, but time reporting not. On server, some of the listening times are OK, but some of them are really big, more than 200 hours. As this service is used to listen to streams, it is not possible or realistic to calculate such value. I am therefore convinced that this reporting is not good. I also tried to replace SystemClock with System#currentTimeMillis, but the values are very big as well. Could somebody tell me, how to measure listening time correctly or provide me some best practices?



from Service time measurement

No comments:

Post a Comment