This is part of my AudioViz project on GitHub. This service broadcasts an Intent (com.app.playing) when it starts to play. I did this because I found that there was a delay between when I started the service, and when the music was playing which caused NullPointerExceptions. Elsewhere in the code, I have a Broadcast receiver listening for this broadcast upon which the rest of initialization code is run.

public class Player extends Service {
	public static MediaPlayer mPlayer;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	public void onCreate() {
	    super.onCreate();
	    mPlayer = MediaPlayer.create(this, R.raw.test);
	    mPlayer.setLooping(true);
	    
	}
	public int onStartCommand(Intent intent, int flags, int startId) {
	    mPlayer.start();
            Intent i = new Intent("com.app.playing");
	    sendBroadcast(i);
	    return START_STICKY;
	}
	public void onDestroy() {
	    if (mPlayer != null)
	    {
              mPlayer.stop();
	      mPlayer.release();
	      mPlayer = null;
	    }
	}

	  public static void startPressed() throws IllegalStateException, IOException
	  {
	    if(mPlayer.isPlaying())
	    {
	      return;
	    }
	    mPlayer.prepare();
	    mPlayer.start();
	  }

	  public static void stopPressed()
	  {
	    mPlayer.stop();
	  }

	  public static MediaPlayer getPlayer() {
		  return mPlayer;
	  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *