I have a Service
which takes in an audio file and plays it with MediaPlayer
. This is how I call my Service
:
private void playAudio(String url) throws Exception {
Intent music = new Intent(this,MusicService.class);
music.putExtra("paths", path);
startService(music);
}
This is my Service
class:
class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
String musicFile;
@Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle e = intent.getExtras();
musicFile= e.getString("paths");
try {
mediaPlayer.prepare();
mediaPlayer.setDataSource(musicFile);
} catch (IllegalArgumentException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IllegalStateException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IOException i) {
// TODO Auto-generated catch block
i.printStackTrace();
}
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
The Service
is never getting executed, the Toast
is never shown, and the MediaPlayer
does not play.
I declare my it in my manifest like this:
<service android:name=".MusicService" android:enabled="true"></service>
I get a force close error, and this IllegalAccessException
in my logs:
java.lang.RuntimeException: Unable to instantiate service unjustentertainment.com.MusicService:
java.lang.IllegalAccessException: access to class not allowed
The exception you get is because the system could not init your service (call its constructor) because its not accessible.
As it says here:
...Make sure the class is declared public...
The class you posted is not public, so make it public.
You need to make your class public. i.e.
public class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
String musicFile;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With