问题
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 play-in 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.
Can anyone suggest what I am doing wrong?
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) {
returnnull;
}
@Override
publicvoid onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);
player.start();
player.setLooping(true);
}
@Override
publicvoid onDestroy() {
super.onDestroy();
player.stop();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
}
回答1:
There are a few things that I see in your code that I would check out if I were in your position.
- You are trying to call "stop" on a member MediaPlayer object "player" in your onDestroy, but in your onCreate you create a MediaPlayer object "player" with your line of code
"MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);"
which i believe creates a player object that you will loose scope of outside of the function.
The 1 line fix for this code is to just use "player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);", this way the member variable is used rather than a local variable
If this were my code I would change the member variable to be called something like m_player or mPlayer so that you know it is a member variable in your code.
(probably a typo) "returnnull;" in onBind should be "return null;"
you also might want to try calling
player.stop(); Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
before you call super.onDestroy()
Let me know if this helps at all
来源:https://stackoverflow.com/questions/2298817/not-able-to-check-android-service-issue