I\'m new to Android, so I have a problem. In Android I want to play background music as soon as my music player starts and have it continue even if the activity changes from
To start playing music you will need to figure out when our application starts. We can do that by extending Application class. Application object is instantiated before any activity and is preserved until our app is terminated by the Android OS. That makes it ideal to control playback only within this object. When we create new class that extends Application we must register it into our manifest.
We have determined when our application is created but what about stopping the music when our application goes from foreground to background? Android offers no out-of-the-box method for determining that. To solve that problem I followed this very good article and part of the solution code was from there.
Code for Application:
package com.example.stackmusic;
import android.app.Activity;
import android.app.Application;
import android.media.MediaPlayer;
import android.os.Bundle;
public class PlayMusicApp extends Application {
private MediaPlayer music;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
music = MediaPlayer.create(this, R.raw.some_music);
}
/**
* All activities created in our application will call these methods on their respective
* lifecycle methods.
*/
class MyLifecycleHandler implements ActivityLifecycleCallbacks {
private int resumed;
private int stopped;
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
public void onActivityDestroyed(Activity activity) {
}
public void onActivityResumed(Activity activity) {
// this is the first activity created
if(resumed == 0) {
music.start();
}
++resumed;
}
public void onActivityPaused(Activity activity) {
}
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
public void onActivityStarted(Activity activity) {
}
public void onActivityStopped(Activity activity) {
++stopped;
android.util.Log.w("test", "application is being backgrounded: " + (resumed == stopped));
// we are stopping the last visible activity
if(resumed == stopped) {
music.stop();
}
}
}
}
Registration in manifest:
You don't want to play music in the UI thread. Ideally create a service for playing music in background thread instead of managing media player in Application object.