Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Service controlling MediaPlayer

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.app.Service;

import android.content.Intent;

import android.media.MediaPlayer;

import android.os.IBinder;

import android.widget.Toast;

public class MyService extends Service {

    private MediaPlayer player;

    @Override
    public IBinder onBind(Intent intent) {

        return null;

    }

    @Override
    public void onCreate() {

        super.onCreate();

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

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

        player.start();

        player.setLooping(true);

    }

    @Override
    public void onDestroy() {

        super.onDestroy();

        player.stop();

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

    }

}
like image 859
ChaluxeDeluxe Avatar asked Feb 19 '10 19:02

ChaluxeDeluxe


People also ask

How can I stop media player in another activity?

How can I stop MediaPlayer in another activity? You can't destroy one activity from another activity. But you can pause the media player by creating a new instance of MediaPlayer in the second activity and callind the 'stop' method !

What is a media player used for?

Media players provide most or all of the following features. They allow users to organize their multimedia collection, play songs and movies, rip CD tracks to MP3 and other audio formats, burn CDs, listen to Internet radio, download content from online music stores and stream content from the Internet.

What is media player Android?

MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network.

How do I turn off media player on Android?

The feature is as simple as tapping and holding on the media card of any app then choosing Dismiss.


1 Answers

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.

like image 131
Ritesh Gune Avatar answered Sep 21 '22 22:09

Ritesh Gune