0

In my app there is a background music, done with service. In my app there are many activities, so I would like the music to play in all of them, but also to turn off when screen turns off or user closes the app. In java of one acitivity I wrote this:

public void onPause() {
    super.onPause();
    stopService(new Intent(Activity.this, Service.class));

}

public void onStop() {
    super.onStop();
    stopService(new Intent(Activity.this, Service.class));

}

public void onResume() {
    super.onResume();
    startService(new Intent(Activity.this, Service.class));

}

public void onRestart() {
    super.onRestart();
    startService(new Intent(Activity.this, Service.class));

}

The problem is when I am switching to another activity, service/music stops. How to make music play in all activities, but also turn off onStop and onPause in all of them? Thank you.

My service:

public class Service extends Service {


private final String TAG = null;
MediaPlayer player;

public IBinder onBind(Intent arg0) {

    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    player = MediaPlayer.create(this, R.raw.music);
    player.setLooping(true); // Set looping
    player.setVolume(100, 100);




}

public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return 1;
}

public void onStart(Intent intent, int startId) {
    // TO DO
}

public IBinder onUnBind(Intent arg0) {
    // TO DO Auto-generated method
    return null;
}


protected void onStop() {
    player.pause();
}

public void onPause() {
    player.pause();
}

@Override
public void onDestroy() {
    player.stop();
    player.release();
}

@Override
public void onLowMemory() {

}

}
Surya Prakash Kushawah
  • 3,185
  • 1
  • 22
  • 42
Old York
  • 73
  • 1
  • 9

1 Answers1

0

you add the player to your application context so that each activity could use it (Android global variable) then you are able to start/pause the player within other activites. A second approach is using a bus framework which transfers the player object between the activities.

Community
  • 1
  • 1
wake-0
  • 3,918
  • 5
  • 28
  • 45