Where to create music player service w.r.t. MediaBrowserServiceCompat

1.1k Views Asked by At

I want to create a MusicPlayer application which leverages the features of MediaBrowserService. While going thru documentation of MediaBrowserServiceCompat, I realized it is a subclass of Service, which means it runs on Application's main UI thread.

But since music player is a long running task, I suppose its best to implement it as an IntentService, rather than as Service.

So I wanted to ask:

  1. Where should I implement my MusicPlayer service?

  2. Should I implement it within MediaBrowserServiceCompat implementation? But will it not make too heavy on UI thread?

  3. Or should I implement it as an IntentService & call it from my MediaBrowserServiceCompat? But it seems bit complex.

Here is my initial code structure

Please suggest.

Thank You

3

There are 3 best solutions below

1
On

Wrong :

I realized it is a subclass of Service, which means it runs on Application's main UI thread.

Doc clearly say :

A Service is an application component that can perform long-running operations in the background

And it also said if you need some kind of long time task, you should implement as Foreground Service.

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
        PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification =
          new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
    .setContentTitle(getText(R.string.notification_title))
    .setContentText(getText(R.string.notification_message))
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(pendingIntent)
    .setTicker(getText(R.string.ticker_text))
    .build();

startForeground(ONGOING_NOTIFICATION_ID, notification);
0
On

The music player I wrote uses background service from which I play the songs.

The problem with this approach is that on devices like Xiaomi or Huawei those services are killed in order to "save" battery life. I guess the best you can do is when your service gets killed you could restart it and start the song again ...

That's the solution I came up with, if anyone has a better idea I would love to hear it.

0
On

You should use Service as a command manager for your music player app. All the play, pause, next and other playback controls should be sent to service, and service will delegate it accordingly. Also Android MediaPlayer has asynchronous methods and associated listeners to notify callers. Please do have a look at it. Please follow google sample code for music player https://github.com/googlesamples/android-UniversalMusicPlayer which addresses basic music player functionalities very well.