I'm trying to use service for a background music.
package com.example.neotavraham;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayMusicService extends Service implements MediaPlayer.OnPreparedListener {
public static final String ACTION_PLAY = "com.example.neotavraham.PLAY";
MediaPlayer mMediaPlayer = null;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.yedid_nefesh);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
return flags;
}
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
I call it from the MainActivity
with the line: startService(new Intent(PlayMusicService.ACTION_PLAY));
and of course I added an intent-filter
<intent-filter>
<action android:name="com.example.neotavraham.PLAY"/>
</intent-filter>
I was looking for a fine solution in the internet but couldn't find one...what should I do?