MediaControllerCompat.Callback only works as a field

574 Views Asked by At

When I register callback in a service which is part of method it is not working - doesn't get any invokes:

@Override
public void onCreate() {
    super.onCreate();

    MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat state) {
            KLog.d(state);
            sendInfoBroadcast(false);
            makeNotification();
            super.onPlaybackStateChanged(state);
        }

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            KLog.d();
            KLog.d(metadata);
            sendInfoBroadcast(false);
            makeNotification();
            super.onMetadataChanged(metadata);
        }
    };
    MediaControllerCompat mediaController = new MediaControllerCompat(this, mediaSessionCompat.getSessionToken());
    mediaController.registerCallback(callback);

}

I need to make it or MediaController a field and then it works:

 private MediaControllerCompat mediaController;
 private MediaControllerCompat.Callback callback= new MediaControllerCompat.Callback() {
        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat state) {
            KLog.d(state);
            sendInfoBroadcast(false);
            makeNotification();
            super.onPlaybackStateChanged(state);
        }

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            KLog.d();
            KLog.d(metadata);
            sendInfoBroadcast(false);
            makeNotification();
            super.onMetadataChanged(metadata);
        }
    };

@Override
public void onCreate() {
    super.onCreate();
    mediaController = new MediaControllerCompat(this, mediaSessionCompat.getSessionToken());
    mediaController.registerCallback(callback);

}

Why? Does the GC kill it? I wasted whole day because of that.

0

There are 0 best solutions below