Android service for managing MediaPlayer

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(); } } 
+6
android service media-player
source share
4 answers

player.stop(); ----- this line should give you a nullPointerException .

private MediaPlayer player; Here you only create a link. But an object created in onCreate() has only a local scope. Create an object with a class level scope, then it will work.

+5
source share

onBind method returns null only if it is a "Local Service". If I understand you correctly, you want to create a remote service.

show the remote service section in this link site.

0
source share

If you have a player object declared local in the OnCreate procedure, delete the local declaration, see below:

 //MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.my_music); player = MediaPlayer.create(MyService.this, R.raw.my_music); 
0
source share

As ** Rick D ** wrote, the problem was declared in Mediaplayer, which you already announced to the player, just put:

 player = MediaPlayer.create(ForegroundService.this, R.raw.my_music); 
0
source share

All Articles