Failed to check issue with Android service.

All I want to do is just control the background music in my application through the service, so I can start it and stop it from any activity.

Everything is fine with me, when I tell the Toast service, when it starts and is destroyed, but as soon as I put the media player into it, instead it starts normally and starts playing music, but as soon as I click the button to stop the service, I I get an error message and the force closes.

Can anyone suggest what I'm 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(); } } 
+2
java android service media-player
source share
1 answer

There are a few things that I see in your code to check if I was in your place.

  • You try to call a “stop” on the “Player” object of the MediaPlayer member 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, in my opinion, creates a player object that you lose outside the function.

The 1 line fix for this code is to simply use "player = MediaPlayer.create (MyService.this, R.raw.oceanwavestest)", so a member variable is used, not a local variable

If it was my code, I would change the member variable to be something like m_player or mPlayer so that you know that this is a member variable in your code.

  • (possibly a typo) "returnnull;" in onBind should be "return null;"

  • you can also try calling

player.stop (); Toast.makeText (this is "Service stopped", Toast.LENGTH_SHORT) .show ();

before calling super.onDestroy ()

Let me know if this helps at all.

0
source share

All Articles