If you want to play background music for your app only, then play it in a thread launched from your app/use AsyncTask class to do it for you.
The concept of services is to run in the background; By background, the meaning is usually when your app UI is NOT VISIBLE. True, it can be used just like you have (If you remember to stop it) but its just not right, and it consumes resources you shouldn't be using.
If you want to peform tasks on the background of your activity, use AsyncTask.
By the way, onStart
is deprecated. When you do use services, implement onStartCommand
.
UPDATE:
I think this code will work for you. Add this class (Enclosed in your activity class).
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(1.0f, 1.0f);
player.start();
return null;
}
}
Now, in order to control the music, save your BackgroundSound object instead of creating it annonymously. Declare it as a field in your activity:
BackgroundSound mBackgroundSound = new BackgroundSound();
On your activity's onResume method, start it:
public void onResume() {
super.onResume();
mBackgroundSound.execute(null);
}
And on your activity's onPause method, stop it:
public void onPause() {
super.onPause();
mBackgroundSound.cancel(true);
}
This will work.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…