【发布时间】:2015-02-24 16:24:46
【问题描述】:
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();
}
}
这是播放背景音乐的服务,如何在按下home键时暂停服务,在程序恢复时恢复服务?这是我的 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));
}
}
我觉得需要用到onPause()和onResume()函数,但是怎么用呢?它应该在服务类或活动类中使用?
还有一点需要考虑,我使用了多个意图,并确保当我更改为 2nd 或其他意图时,服务仍在运行,这意味着更改意图不会停止播放背景音乐...除非 home按钮被按下或退出程序(这个我已经完成了)。
【问题讨论】: