我目前正在开发一个移动应用,作为我课程的最终项目。我的问题是当我按下手机的 HOME 按钮时,我使用 Service 播放的背景音乐没有停止。
我希望你能帮助我解决我的问题。始终保持安全,我的开发人员。
BgMusicService.class
package com.example.biowit;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class BgMusicService extends Service {
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.bg_music);
player.setLooping(true);
player.setVolume(100, 100);
player.setOnCompletionListener(mp -> player.release());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
player.setOnCompletionListener(mp -> player.release());
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.release();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
}
未检测到错误日志
答案 0 :(得分:0)
在您的 Activity 生命周期 方法中调用将启动/停止服务的 Intent,或者甚至更好,而不是启动/停止整个服务,只需发送 Intent 来播放暂停音乐并保持服务运行。
根据您的应用结构选择 onPause/onResume
或 onStart/onStop