Android Service controlling MediaPlayer

0 votes
asked Feb 19, 2010 by chaluxedeluxe

All I want to do is simply control background music in my app through a service so I am able to start it and stop it from any activity.

I have everything set up perfectly when I tell the service to Toast when it is started and destroyed but as soon as I put the media playin in there instead It starts fine and starts playing the music but as soon as a click a button to stop the service I get an error and a force close.

PLEASE someone help me see what I am doing wrong.. I am pretty new to android developing I'm guessing it's going to be something easy.

Here is my code:


import android.content.Intent;


import android.os.IBinder;

import android.widget.Toast;

public class MyService extends Service {

    private MediaPlayer player;

    public IBinder onBind(Intent intent) {

        return null;


    public void onCreate() {


        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();

        MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.my_music);




    public void onDestroy() {



        Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();



3 Answers

0 votes
answered Feb 11, 2011 by ivorycirrus

onBind method returns null only if it is a "Local Service". If I understand you correctly, you want to create remote service.

show the remote service section in this reference site.

0 votes
answered Feb 3, 2012 by ritesh-gune

player.stop();----- this line must be giving you nullPointerException.

private MediaPlayer player; here you are creating only reference.But object you are creating in onCreate() has local scope only. Please create an object having class level scope, then it will work.

0 votes
answered Feb 9, 2016 by rick-d

You have the player object declared local to the OnCreate Procedure, remove the local declaration, see below:

//MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.my_music);
player = MediaPlayer.create(MyService.this, R.raw.my_music);
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter