我正在使用服务播放背景音乐。问题是,当我完成活动后,音乐会继续播放。
以下是启动服务的主要活动代码
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
startService(svc);
BackgroundSoundService.java
public class BackgroundSoundService extends Service {
private static final String TAG = null;
public static MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("atMedia", "Backround Music playing");
player = MediaPlayer.create(this, R.raw.background);
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;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
答案 0 :(得分:3)
您必须在服务中调用selfStop()方法。 或使用stopService()API
答案 1 :(得分:3)
尝试从MainActivity停止服务:
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
stopService(svc);