大家好,我正在制作一个android游戏应用程序,我想为我的游戏制作一个背景音乐。我在stackoverflow中发现了一些代码,但它不能正常工作,因为当我按下back按钮或home按钮时,音乐仍然在播放,即使我将它从任务中移除它仍然在运行,这意味着onPause或onDestroy不工作。有人能帮帮我吗,谢谢!
下面是我找到代码Android background music service的链接
发布于 2018-09-09 19:36:24
1)首先将你的music.mp3放入raw文件夹
2)将清单中的服务声明为<application>元素的子元素
<service android:name=".SoundService" android:enabled="true"/>3)添加MusicService.java类:
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class SoundService extends Service {
MediaPlayer mPlayer;
@Override
public void onCreate() {
mPlayer = MediaPlayer.create(this, R.raw.music);
mPlayer.setLooping(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
mPlayer.stop();
mPlayer.release();
super.onDestroy();
}
}4)运行\停止活动中的服务:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
startService(new Intent(MainActivity.this, SoundService.class));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed() {
stopService(new Intent(MainActivity.this, SoundService.class));
super.onBackPressed();
}
@Override
protected void onPause() {
// When the app is going to the background
stopService(new Intent(MainActivity.this, SoundService.class));
super.onPause();
}
@Override
protected void onDestroy() {
// when system temporarily destroying activity
stopService(new Intent(MainActivity.this, SoundService.class));
super.onDestroy();
}
}发布于 2018-09-09 18:50:41
我认为你将音乐作为一种服务来播放,你必须在你的活动的onPause和onDestroy中销毁这种服务。
https://stackoverflow.com/questions/52243410
复制相似问题