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(); } }
java android service media-player
ChaluxeDeluxe
source share