Kris B
Kris B

Reputation: 3578

Service.startForeground() in MediaBrowserServiceCompat

I am getting this error shown in the Android Dashboard crash logs:

Context.startForegroundService() did not then call Service.startForeground() (no location available)

I'm aware of the Background Limitations introduced in Oreo and have read through this post.

However, I'm still getting this error thrown for a small percentage of my users who are running Android Wear 8.0. What makes it confusing is it's not all users running 8.0.

According to the documentation, if you call Context.startForgroundService() you must show a notification by calling startForeground() in the service within 5 seconds (I'm assuming MediaBrowserCompat is calling Context.startForgroundService()).

However, I'm not sure if I need to do that if I'm using a MediaBrowserServiceCompat. I do show a foreground notification when the user hits play to start audio playback.

public class MediaActivity {

    private MediaBrowserCompat mMediaBrowserCompat;

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

        mMediaBrowserCompat = new MediaBrowserCompat(
                this,
                new ComponentName(this, MediaPlayerService.class),
                mMediaBrowserCompatConnectionCallback,
                getIntent().getExtras()
        );

        mMediaBrowserCompat.connect();     
    }
}

private MediaBrowserCompat.ConnectionCallback mMediaBrowserCompatConnectionCallback = new MediaBrowserCompat.ConnectionCallback() {

    @Override
    public void onConnected() {
        super.onConnected();
        final MediaControllerCompat mcc = new MediaControllerCompat(MediaActivity.this, mMediaBrowserCompat.getSessionToken());
        mcc.registerCallback(mMediaControllerCompatCallback);
        MediaControllerCompat.setMediaController(mActivity, mcc);
    }
};

public class MediaPlayerService extends MediaBrowserServiceCompat {
    @Override
    public void onCreate() {
        super.onCreate();

        //Should I add a startForeground notification here

    }
}

private MediaSessionCompat.Callback mMediaSessionCallback = new MediaSessionCompat.Callback() {
    @Override
    public void onPlay() {
        super.onPlay();

        final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelID)

        ...
        startForeground(101, builder.build());
    }

    @Override
    public void onPause() {
        super.onPause();
    }
};

Upvotes: 1

Views: 1536

Answers (1)

NitVid
NitVid

Reputation: 49

You have to use the startForegroundService before calling startforeground to attach the foreground notification if you are running audio mediaCompact service , this will not destroy by the system due to background limitation.

Upvotes: 1

Related Questions