MediaPlayer Service不播放音乐

MediaPlayer Service不播放音乐

问题描述:

我试图为我的应用程序设置背景音乐,我已经尝试了一些在因特网中找到的例子,但任何人都可以使用,我的应用程序不显示任何背景音乐。MediaPlayer Service不播放音乐

这里是我的服务类代码:

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); 
     } 
} 

不要忘记在manifest注册您的服务:

<service android:name="com.your.package.MusicService" 
     android:enabled="true"/> 
+0

好吧,我做到了,但现在它抛出我一个的RuntimeException:无法实例化的服务。任何建议? – 2014-10-31 18:58:43

+0

看看这个:http://stackoverflow.com/questions/5027147/android-runtimeexception-unable-to-instantiate-the-service – 2014-10-31 19:04:09

+0

基于该链接,我认为你需要为你的服务添加一个构造函数 – 2014-10-31 19:04:44

嘿请确保你在清单文件中注册它。

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
... 
<service android:name="MusicService " android:enabled="true"></service> 
</application> 

享受...