'Playing MediaPlayer across all activities

I have an Activity which extends a BaseActivity, in which in the BaseActivity it also creates a Thread in order to play a MediaPlayer throughout all activities in a different Thread, here is my code:

In my MainActivity:

public class MainActivity extends BasedActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    beginBGMusic();
  }
}

Within my BasedActivity:

public class BasedActivity extends AppCompatActivity {

MediaPlayer BGMusicPlayer;
Thread BGMusic;

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

@Override
protected void onResume() {
    super.onResume();
}

protected void beginBGMusic(){
    BGMusic = new Thread(){

        public void run(){
            BGMusicPlayer = MediaPlayer.create(this,R.raw.music.mp3);
        }
    };

    BGMusic.start();
  }
}

However, the MediaPlayer.create() expects a context, I don't understand how should I set the context if its in a Thread and also in a different class.

Does anyone know how to resolve the problem with my approach?

Thanks!



Solution 1:[1]

/**
 * Class MediaManager created on 11/07/16 - 4:01 PM.
 * All copyrights reserved to the Zoomvy.
 * Class behaviour is to initialize and play a media file on notification
 */
public class MediaManager {
    /**
     * SingleTon instance
     */
    private static MediaManager sInstance;

    private Context mContext;

    private MediaManager(Context context) {
       mContext = context.getApplicationContext();
    }

    public static MediaManager getInstance(Context context) {
        if (null == sInstance) {
            synchronized (MediaManager.class) {
                sInstance = new MediaManager(context);
            }
        }
        return sInstance;
    }
}

Above is the singleton class for the Media Manager. Here you can further define the media player and it will be single instance for all your activity.

But still I recommend to use a service instead of a thread.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ola Ström