I have a media player service that plays music in the background of my app throughout activities like :
public class Music extends Service {
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_NOT_STICKY;
}
public void onDestroy() {
player.stop();
player.release();
stopSelf();
super.onDestroy();
}
The problem is that when the user changes app or goes to home screen of phone(app goes in the background) the music is still playing.
I have tried to stop it in onStop
and onDestroy
method but this stops the music when I change activities which is something that I don't want(I want the music to keep playing when user navigates through activities).
Update
I tried with broadcast:
I added
LocalBroadcastManager.getInstance(this).registerReceiver(StateReceiver, new IntentFilter("status"));
in onCreate of music Service and a method to receive events :
private BroadcastReceiver StateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String status = intent.getStringExtra("status");
if (parseInt(String.valueOf(status)) == 0) {
player.stop();
}else{player.start();}
}
};
And in Application class I did this:
public class app_class extends Application implements Application.ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;
private static String currentActivity;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
currentActivity = activity.getClass().getSimpleName();
}
public static String getCurrentActivity() {
return currentActivity;
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
send_status(1);
}
@Override
public void onActivityPaused(Activity activity) {
send_status(0);
}
private void send_status(int status_counter) {
Intent intent = new Intent("status");
intent.putExtra("status", String.valueOf(status_counter));
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
But the music wont resume
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…