1

I'm trying to set up a background music for my app, I've already tried some examples that I found in internet but anyone works, my app doesn't display any background music.

Here is my service class code:

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

And here is where and how I declare it on my MenuActivity class :

@Override
protected void onStart() {
      super.onStart();
      if(playIntent == null){
        playIntent = new Intent(this, MusicService.class);
        startService(playIntent);
      }
}
Roman Panaget
  • 1,578
  • 12
  • 21

2 Answers2

2

Dont forget to register your service in the manifest :

    <service android:name="com.your.package.MusicService" 
        android:enabled="true"/>
Blaze Tama
  • 10,828
  • 13
  • 69
  • 129
1

Hey make sure u register it in manifest file.

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

Enjoy...

Ganesh Katikar
  • 2,620
  • 1
  • 26
  • 28