Nick Otten
Nick Otten

Reputation: 712

Managing a class between activities

I'm currently working on a project for my study, in this project I have to create a small android game. If all goes well my game is gonna look more or less like the old pokemon games for the gameboy.

The game is build using several activities (a splash screen, menu, game view, combat view and so on). Right now I have most things working. But there is one thing that bothers me and where people around me can't give a clear answer about.

In the game I have a class called MusicPlayer.java. This class is used to play the background music during most of the Activities. Right now I Initialise this class in the oncreate of a activity and set it to play a .mp3 file from the res/raw folder. When I start a different activity i call the .close() from the MusicPlayer.

public class MusicPlayer {

private MediaPlayer player;

public void Play(int songid, Context cont)
{
    player = MediaPlayer.create(cont, songid);
    try {
            player.start();
    }
    catch (Exception e)
    {
        Log.d("MusicPlayer","Something wend wrong while starting the song!");
        Log.d("ERROR",e.toString());
    }
}


public void close()
{
    if(player != null)
    {
        player.stop();
        player.release();
        player = null;
    }
}

Creating this class over and over again feels a little clumsy and it forces me to start a new song with every activity. I've also noticed that when starting a new activity the old activity keeps running. If I don't call the .close the music keeps on playing in the next window. Is there a way to acces this object again? For example to call a method that changes/stops the song? I already did some google attempts on this but I can't get the object to move with the Activity. It didn't fit in the .putExtras() nor was I able to create a Parcelable of it.

Right this is quite a wall-o-text now and I'm sorry for that...But this limitation to my project really bugs me and with my very limited knowledge of android/java programming (I'm used to .net, only working in java/android for a month now) it will improve, so if anyone knows something I should look into that would be great!

Upvotes: 0

Views: 104

Answers (1)

nicopico
nicopico

Reputation: 3636

You can use a Intent Service to play the music, using intents to communicate from your activities (for example to change song, stop the music when your app is not in the foreground, etc.)

Upvotes: 1

Related Questions