Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a Service throws an IllegalAccessException

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
like image 627
Waggoner_Keith Avatar asked Nov 26 '11 16:11

Waggoner_Keith


Video Answer


2 Answers

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.

like image 113
Jong Avatar answered Sep 18 '22 02:09

Jong


You need to make your class public. i.e.

 public class MusicService extends Service implements OnCompletionListener {
          MediaPlayer mediaPlayer;
           String musicFile;
like image 24
Asher Avatar answered Sep 21 '22 02:09

Asher