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() {
}
}