Search code examples
androidandroid-serviceandroid-mediaplayer

Cannot create MediaPlayer inside thread


I have a Service that starts a thread, where I need to create a MediaPlayer:

Inside onStartCommand I call the main function that runs a thread.

public int onStartCommand(Context context, Intent intent, int flags, int startId) {
    Log.e(TAG, "onStartCommand");

    doTask(context);
    return START_STICKY;
}


void doTask(Context context) {

    isActive = true;
    thread = new Thread(new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void run() {
            try {
                threadLoop(context);
            } 
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();
    Log.e(TAG, "Thread started");
}

After this, inside threadLoop I am trying to create a MediaPlayer


MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer = MediaPlayer.create(context, AudioData);

but I can't do anything with the 1st context parameter. I tried to send context and get the base one, but it doesn't work.

Maybe I should use another service for MediaPlayer?

Thank you in advance

Update

Error: Cannot resolve method 'create(android.content.Context, short[])'.


Solution

  • You're passing in the wrong data to the second parameter. The first parameter is fine. The second is a resource id or a Uri, not a short[]. If the short array is supposed to be audio data (like the raw .wav data), write it to a file and pass it the URI of that file.

    Also, passing context to a Thread like that is dangerous and can lead to memory leaks. You need to make sure the thread is ended when the service is ended to prevent it.