I'm having trouble adding background music to my app. I have three activities and I would like the music to keep playing regardless of whether the user switches activities or not. I am currently using a service to play the music but this results in the music starting and stopping every time a different activity starts.
I have found this solution several times throughout forums but it doesn't seem work:
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
}
}
You're supposed to add it to every activities onPause, and I did that and it still didn't work. The music doesn't stop when you switch between activities, but it also doesn't stop when you exit the app.
Thanks in advance for the help.