Jackyto
Jackyto

Reputation: 1599

Service or Activity for playing music in MediaPlayer App

I would like to develop a media player for Android on my own but I have a conception issue : should I use a Service or an Activity just for the player?

I have Fragments in my App and I would like to play a song when I click on one of the items within my music lists but I don't really know which of those 2 technologies I should use to allow music to keep playing even during navigation or outside the app.

Does it better to start a new Activity when a song is played and then keep the Activity running or launch a Service waiting for some events?

Thanks in advance.

Upvotes: 1

Views: 3860

Answers (2)

Shankar Regmi
Shankar Regmi

Reputation: 874

The best solution for your app may be

i) Visualize your app with frontend ( like selecting music to play, pause, forward and other features )

ii) start service that runs in background which continues the activity process in background even if the activity is closed ..

You can accomplish this by implementing following ->

public class MyService extends Service implements MediaPlayer.OnPreparedListener {
    private static final String ACTION_PLAY = "com.example.action.PLAY";
    MediaPlayer mMediaPlayer = null;
    public int onStartCommand(Intent intent, int flags, int startId) {
        ...
        if (intent.getAction().equals(ACTION_PLAY)) {
            mMediaPlayer = ... // initialize it here
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.prepareAsync(); // prepare async to not block main thread
        }
    }

    /** Called when MediaPlayer is ready */
    public void onPrepared(MediaPlayer player) {
        player.start();
    }
}

I think this is somehow helpful to you ..

Upvotes: 2

nikis
nikis

Reputation: 11234

If you want music playing in background, you should definitely use Service. Use activity only for UI-related operations. Since playing music is not UI-related operation, it should be done in Service. Please take a look here: http://developer.android.com/guide/topics/media/mediaplayer.html

Upvotes: 2

Related Questions