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 get an error and the force closes.
PLEASE someone help me understand what I'm doing wrong. I am new to Android development. I guess it will 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(); } }
android service media-player
ChaluxeDeluxe
source share