Reputation: 1724
public class BackgroundMusicService extends Service
{
int currentPos;
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
MediaPlayer player;
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.tornado);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.seekTo(currentPos);
player.start();
return 1;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
}
public void onPause()
{
player.pause();
}
@Override
public void onDestroy() {
player.stop();
currentPos = player.getCurrentPosition();
}
}
This is the service that play the background music, how to pause the service when the home button is pressed and resume the service when the program is resume? and here is my MainActivity:
public class MainActivity extends ActionBarActivity
{
int request_code = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getBaseContext(), BackgroundMusicService.class));
}
@Override
protected void onDestroy()
{
super.onDestroy();
stopService(new Intent(getBaseContext(), BackgroundMusicService.class));
}
}
I think need to use onPause()
and onResume()
function, but how to use it? and it should be use in service class or the activity class?
One more thing need to consider, I used multiple intent, and make sure that when I change to 2nd or others intents, the service is still running, means that changing intent will not stop playing the background music...unless home button is pressed or quit the program(this one I already done).
Upvotes: 1
Views: 6229
Reputation: 7599
You have your onPause and onResume methods. You generally don't need to extend the Application class but instead use it in your Activity (esp if your app only has one Activity).
However, why start and stop the service? Why not just pause/unpause the music? You can send an intent to pause/unpause (or even toggle) the music playback.
Upvotes: 1