【发布时间】:2014-10-31 18:39:01
【问题描述】:
我正在尝试为我的应用设置背景音乐,我已经尝试了一些我在互联网上找到的示例,但任何人都可以使用,我的应用不显示任何背景音乐。
这是我的服务类代码:
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
class MusicService extends IntentService {
MediaPlayer mediaPlayer;
public MusicService(){
super("MusicService");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this, R.raw.backtrackquiz);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
这是我在 MenuActivity 类中声明它的位置和方式:
@Override
protected void onStart() {
super.onStart();
if(playIntent == null){
playIntent = new Intent(this, MusicService.class);
startService(playIntent);
}
}
【问题讨论】:
标签: java android service android-mediaplayer