Starting a Service throws an IllegalAccessException

心不动则不痛 提交于 2020-07-16 05:30:34

问题


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

回答1:


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.




回答2:


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

 public class MusicService extends Service implements OnCompletionListener {
          MediaPlayer mediaPlayer;
           String musicFile;


来源:https://stackoverflow.com/questions/8280035/starting-a-service-throws-an-illegalaccessexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!